Tommy Rozgonyi
Tommy Rozgonyi

Reputation: 51

Optional closures in swift 5

I have been having trouble figuring out how to write an optional closure for swift 5. I have found a lot of explanations that are a few years old and none of them seem to work now. I have tried:

func test(completion: (() -> Void)?){
    completion()
}

and other variations of that. Any help is much appreciated.

Upvotes: 0

Views: 231

Answers (1)

TylerP
TylerP

Reputation: 9829

I'm assuming when you say "how to write an optional closure" you mean "how to call an optional closure", because you've written the closure parameter just fine, but you're just not calling it correctly.

To call an optional closure, you need to unwrap it first. Either:

completion?()

or:

if let unwrappedCompletion = completion {
    unwrappedCompletion()
}

Upvotes: 2

Related Questions