๐ŸŽ“ A1Learner
๐Ÿ”
0 of 36 lessons completed

Swift Nested Functions

A nested function is a function defined inside another function. Code outside the outer function cannot call it.

A helper inside a function

The line function exists only inside showReport. One call to showReport runs the helper twice around the title.

func showReport() {
    func line() {
        print("---")
    }
    line()
    print("Report")
    line()
}
showReport()

Reading an outer parameter

The decorate function reads the word parameter of its outer function. The loop calls decorate once per repeat and joins the pieces.

func repeatWord(word: String, times: Int) -> String {
    func decorate() -> String {
        word + "!"
    }
    var result = ""
    for _ in 1...times {
        result += decorate()
    }
    return result
}
print(repeatWord(word: "go", times: 3))

Stepping a captured variable

The advance function adds five to position and records each new spot. The walk function calls it once per step and returns the recorded positions.

func walk(steps: Int) -> [Int] {
    var position = 0
    var visited: [Int] = []
    func advance() {
        position += 5
        visited.append(position)
    }
    for _ in 1...steps {
        advance()
    }
    return visited
}
print(walk(steps: 3))
print(walk(steps: 1))

Example

func makeTicks(count: Int) -> [Int] {
    var remaining = count
    var ticks: [Int] = []
    func tick() {
        remaining -= 1
        ticks.append(remaining)
    }
    for _ in 1...count {
        tick()
    }
    return ticks
}
print(makeTicks(count: 3))

Key points

  • A nested function is written inside the body of its outer function.
  • Only code inside the outer function can call the nested function.
  • A nested function can read the parameters and variables of its outer function.
  • A nested function can also change a variable declared in its outer function.
  • Each call to the outer function starts with fresh local variables.

In this example, the tick function lowers the remaining variable from the outer function on every call. Three calls record 2, then 1, then 0 in the ticks array. The walk through the array prints the three values in order.

Note

A nested helper stays hidden, so its name cannot clash with names elsewhere in the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Where can a nested function be called from?