Swift Closures

Closures are self-contained blocks of functionality. Swift closures are concise thanks to shorthand syntax.

Basic Closure

SWIFT
let greet = { (name: String) -> String in
    return "Hello, \(name)!"
}
print(greet("Sita"))

As a Function Parameter

SWIFT
func perform(action: () -> Void) {
    action()
}

perform { print("Done!") }

Shorthand Syntax

SWIFT
let numbers = [5, 2, 8, 1, 9]

// Full syntax
let sorted = numbers.sorted(by: { (a: Int, b: Int) -> Bool in return a < b })

// Shorthand — infer types, omit return
let sorted2 = numbers.sorted(by: { $0 < $1 })

// Even shorter — operator function
let sorted3 = numbers.sorted(by: <)

Trailing Closure

SWIFT
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0, +)

Capturing Values

Closures capture variables from their surrounding scope:

SWIFT
func makeCounter() -> () -> Int {
    var count = 0
    return {
        count += 1
        return count
    }
}

let counter = makeCounter()
counter() // 1
counter() // 2