Menu
Coddy logo textTech

Trailing Closures

Part of the Logic & Flow section of Coddy's Swift journey — lesson 39 of 56.

When a closure is the last argument to a function, you can write it outside the parentheses. This is the trailing-closure form, and it's how Swift code reads naturally.

let nums = [1, 2, 3]
// Standard form
let a = nums.map({ $0 * 2 })
// Trailing-closure form
let b = nums.map { $0 * 2 }

If the closure is the only argument, the parentheses disappear too. That's why everything you've seen so far reads like a custom control structure.

You can write your own functions to take closures the same way:

func repeatN(_ n: Int, action: () -> Void) {
    for _ in 0..<n {
        action()
    }
}
repeatN(3) {
    print("hi")
}

The trailing-closure form makes repeatN(3) { ... } read like a built-in loop. That's the point: control structures you build yourself look just like the ones from the standard library.

challenge icon

Challenge

Easy

Define a function collect that:

  • Takes an integer n and a closure builder: (Int) -> String
  • Calls builder for each i from 1 through n (inclusive) and returns the array of resulting strings

Read an integer from stdin, call collect with that integer using a trailing closure that produces "i=<i>" for each value, and print the joined result with ,.

For input 4, the output is i=1,i=2,i=3,i=4.

Cheat sheet

Trailing closure syntax: when a closure is the last argument, it can be written outside the parentheses. If it's the only argument, parentheses are omitted entirely.

let nums = [1, 2, 3]
let a = nums.map({ $0 * 2 }) // standard
let b = nums.map { $0 * 2 }  // trailing closure

Custom functions can accept closures the same way, making them read like built-in control structures:

func repeatN(_ n: Int, action: () -> Void) {
    for _ in 0..<n {
        action()
    }
}
repeatN(3) {
    print("hi")
}

Try it yourself

let n = Int(readLine()!)!

// TODO: func collect(_ n:Int, builder:(Int)->String) -> [String]
// then call collect(n) { ... } and print joined with ","
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow