Pull down to refresh

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.

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

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 multiple configurations with Xcode Test Plan.

Read More
Unit testing in Kotlin with JUnit 5 and MockK

Unit testing in Kotlin with JUnit 5 and MockK

I recently discovered MockK, a mocking library created for Kotlin. Let's see how it is possible to write modern unit tests with MockK + JUnit 5.

Read More
Spring Boot + Kotlin Rest client cheatsheet: RestTemplate and Webclient

Spring Boot + Kotlin Rest client cheatsheet: RestTemplate and Webclient

During the last months I worked a lot with Spring Boot backend applications. In this post I explain how you can consume a REST api from a Spring Boot application using RestTemplate and (the new) WebClient.

Read More