简体   繁体   中英

How to skip completion handler in Swift

I have one function which return Int value in completion handler, however sometimes, I want to skip completion handler while calling from other class and just have Int value. Below is my code. Here totalEvents is with completion handler.

Like I need to call below method

let initialDBCount = self.totalEvents()

func totalEvents(completion: @escaping (_ eventsCount: Int? ) -> Void ) {

    self.fetchEvents(forPredicate: nil, withSort: nil, andLimit: nil, completion: { (events) -> Void in
        guard let fetchEvents = events else {
            return
        }
        if fetchEvents.count > 0 {
            completion(fetchEvents.count)
        }
    })
}

Make the completion handler as optional and set nil as its default value , ie

func totalEvents(completion: ((_ eventsCount: Int?)->())? = nil)

Usage:

totalEvents can be called in both the ways,

1. Without completion handler

totalEvents()

2. With completion handler

totalEvents { (value) in
    print(value)
}

Make optional the completion (_eventsCount: Int?) -> () )? = nil or call the completion like

  if fetchEvents.count > 0 {
    completion(fetchEvents.count)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM