BudiBadu Logo
Samplebadu

Swift by Example: Closures

Swift 5.x

Explore Swift closures with this code example covering full closure syntax, type inference, implicit returns, shorthand argument names using dollar signs, trailing closure syntax, and capturing values from surrounding context.

Code

let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]

// Full syntax
var reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
    return s1 > s2
})

// Type inference and implicit returns
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 })

// Shorthand argument names
reversedNames = names.sorted(by: { $0 > $1 })

// Trailing closure syntax (preferred when closure is last arg)
reversedNames = names.sorted { $0 > $1 }

// Capturing values
func makeIncrementer(amount: Int) -> () -> Int {
    var total = 0
    return {
        total += amount
        return total
    }
}

Explanation

Closures are self-contained blocks of functionality that can be passed around and used in your code. They are similar to lambdas in other languages. Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables.

Swift provides several syntax optimizations for closures to make them concise. You can rely on type inference to omit parameter and return types. For single-expression closures, the return keyword is implicit. Swift also provides shorthand argument names like $0, $1, etc., allowing you to omit the parameter list entirely.

If a closure is the last argument to a function, you can use trailing closure syntax. This allows you to write the closure block outside of the function's parentheses, which looks much cleaner, especially for long closures. This pattern is widely used in Swift APIs and makes code more readable.

Code Breakdown

4
in separates the closure parameters/return type from the body.
9
{ s1, s2 in s1 > s2 } uses type inference and implicit return.
12
$0 > $1 uses shorthand argument names for concise syntax.
14
names.sorted { ... } is trailing closure syntax with parentheses omitted.