blog logo
CHICIO CODING
Coding. Drawing. Fun.
HomeBlogArtAbout me
blog logo
CHICIO CODING
Coding. Drawing. Fun.

Swift Closure: definition and syntax

In this post I will talk about Swift closure: what they are and their syntax.


As reported on the official Apple swift documentation closures are:

Closures are self-contained blocks of functionality that can be passed around and used in your code. They can capture and store references to any constants and variables from the context in which they are defined.

Closures are in many ways what blocks are in Objective-C (or lamba function in other languages). As it was for blocks, it is not easy to remember their syntax. This post is intended to be a reference for me (and you, readers emoji-wink) about closure syntax. You could also take a look at [F%&£&g closure syntax](http://fuckingclosuresyntax.com "F%&£&g closure syntax").

Declared as a variable (valid also for let constants):

var closure: (parameters) -> returnType

Declared as an optional variable:

var closure: ((parameters) -> returnType)?

Declared as a type alias:

typealias ClosureType = (parameters) -> returnType

Declared as a function parameter and then call that function:

func myFunction(closure: (parameters) -> returnType)  {
    ...
}
...

/** You can explictly write the type of parameters. **/

//Call with round brackets.
myFunction(closure: { (parameters) -> returnType in
    ...
})

//Call without round brackets (only if closure is the last parameter).
myFunction { (parameters) -> returnType in
    ...
}

There is also the possibility to use a shorthand for the parameter: you can call them using $ followed by the index of the argument in the call. Last but not least, you can capture self and avoid retain cycle using [unowned self] before the parameters. Go and show to the world the power of closure in Swift!! emoji-sunglasses