๐ŸŽ“ A1Learner
๐Ÿ”

Swift Closures

A closure is a block of code that a program can store and run later. A constant can hold a closure just like a value.

A closure in a constant

The braces hold one parameter and one expression after the word in. The constant name works as the call name in both prints.

let double = { (n: Int) -> Int in n * 2 }
print(double(7))
print(double(3))

A closure that answers true or false

The result type in this closure is Bool. The two calls print false for 7 and true for 20.

let isBig = { (n: Int) -> Bool in n > 10 }
print(isBig(7))
print(isBig(20))

Sorting names by length

The closure sits after the sorted call as a trailing closure. It compares the counts of two names at a time and the printed order runs shortest first.

let names = ["Carlos", "Ana", "Bo"]
let byLength = names.sorted { $0.count < $1.count }
print(byLength)

A closure that changes an outside variable

The closure body adds one to a variable declared before it. Two calls lift the count to two and the print proves the change stuck.

var counter = 0
let step = { counter += 1 }
step()
step()
print(counter)

Example

let greet = { (name: String) -> String in "Hi, " + name }
print(greet("Ana"))
print(greet("Carlos"))

Key points

  • A closure stores a block of code in a constant.
  • Curly braces wrap a closure body.
  • The word in separates the parameter list from the body.
  • Calling a stored closure uses the constant name and parentheses.
  • The shorthand names $0 and $1 stand for the first and second inputs.
  • A closure can read and change a variable declared outside it.

In this example, the greet constant stores a closure that takes one String. The first call passes Ana and prints Hi, Ana. The second call passes Carlos and prints Hi, Carlos.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Swift Compiler

Exercise

What does $0 mean inside a short closure?