Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

optional closure property in Swift

Tags:

ios

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?

like image 545
Sean Danzeiser Avatar asked Jun 11 '14 18:06

Sean Danzeiser


People also ask

How many types of closures are there in Swift?

As shown in the above table, there are three types of closures in Swift, namely global functions, nested functions, and closure expressions. They differ in several aspects, including their use scopes, their names, and whether they capture values, which will be discussed more in a later section.

What is Clouser in Swift?

In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World . Before you learn about closures, make sure to know about Swift Functions.

Why do we need closures in Swift?

Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.

What is trailing closure in Swift?

A trailing closure is written after the function call's parentheses, even though it is still an argument to the function. When you use the trailing closure syntax, you don't write the argument label for the closure as part of the function call.


1 Answers

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? 
like image 188
Jiaaro Avatar answered Sep 21 '22 05:09

Jiaaro