Sjakelien
Sjakelien

Reputation: 2317

Ignore completion handler Swift

I have this function:

func getEvents(completion:@escaping (Bool) -> ()) {
    //here I do some async stuff 
    completion(asyncstuffresult)
}

In some cases, I want to wait for the result of this function, so I call it like this

getEvents { (success) in
    //whatever
}

However, sometimes I want to just fire the function, not really caring about how, or specifically when it is performed.

In that case, I would prefer to call it like this

getEvents()

for the sake of cleanliness

Is there a syntax that allows me to do so?

Upvotes: 2

Views: 2477

Answers (2)

AamirR
AamirR

Reputation: 12218

Change your completion to be an optional, like so:

func getEvents(completion:@escaping ((Bool) -> Void)? = nil) {
    //here I do some async stuff 
    completion?(asyncstuffresult)
}

Notice the optional ? above in completion?(asyncstuffresult), it executes the completion only if given. And you will be able to achieve a desired usage (without necessarily having to pass a completion handler)

getEvents()

Upvotes: 2

pacification
pacification

Reputation: 6018

1. You can change your func to

func getEvents(completion: @escaping ((Bool) -> Void)? = nil)

as Apple does for

func dismiss(animated flag: Bool, completion: (() -> Void)? = nil)

2. Another way is to set "empty" handler as default value to closure:

func getEvents(completion: @escaping ((Bool) -> Void) = { _ in })

All cases allow you to call func as getEvents() without closure parameter.

Upvotes: 4

Related Questions