blog logo

CHICIO CODING

Dirty clean code. Creative Stuff. Stuff.

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

Recent posts

A Domain Driven Design dictionary for newbies
A Domain Driven Design dictionary for newbies

In the last months, I started to hear a lot of stuff about Domain Driven Design. What is DDD? What does it try to solve? This is a post for all the ne...

Read More
How to test your Swift source code on Linux: locally and on Github Actions
How to test your Swift source code on Linux: locally and on Github Actions

Quick tips (useful for open source projects) for testing your Swift source code on Linux locally and with Github Actions.

Read More
Better organize tests and run them against multiple configuration with Xcode Test Plan
Better organize tests and run them against multiple configuration with Xcode Test Plan

Recently I added a lot of Unit and UI tests to RangeUISlider, one of my open source projects. Let's see how I grouped them and run them against multip...

Read More