Reputation: 1257
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)
}
})
}
Upvotes: 0
Views: 895
Reputation: 24341
Make the completion
handler as optional and set nil
as its default value, i.e.
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)
}
Upvotes: 1
Reputation:
Make optional the completion (_eventsCount: Int?) -> () )? = nil or call the completion like
if fetchEvents.count > 0 {
completion(fetchEvents.count)
}
Upvotes: 0