49

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?

Sean Danzeiser
  • 9,141
  • 12
  • 52
  • 90

1 Answers1

77

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?
Jiaaro
  • 74,485
  • 42
  • 169
  • 190