Sean Danzeiser
Sean Danzeiser

Reputation: 9243

optional closure property in Swift

How do you declare an optional closure as a property in Swift?

I am using this code:

    var respondToButton:(sender: UIButton) -> Bool

but the compiler complains that the property is not initialized by the end of the initializer. I believe I can solve this issue by declaring the var as an optional, however, I can not find the correct syntax.

How do I declare this closure property as an optional?

Upvotes: 49

Views: 12946

Answers (1)

Jiaaro
Jiaaro

Reputation: 76978

I believe you just need to wrap the closure type in parenthesis, like so:

var respondToButton:((sender: UIButton) -> Bool)?

Alternatively if this is a closure type you're going to use often you can create a typealias to make it more readable:

typealias buttonResponder = (sender: UIButton) -> Bool

then in your class:

var respondToButton:buttonResponder?

Upvotes: 77

Related Questions