Nested Functions and Scope

Swift’s function definitions can be nested. Nested functions are declared and implemented within the definition of another function. The nested function is not available outside of the enclosing function. This feature is useful when you need a function to do some work, but only within another function. Let’s look at an example.

Listing 12.9  Nested functions

...
func areaOfTriangle(withBase base: Double, andHeight height: Double) -> Double {
    let numerator = base * height
    func divide() -> Double {
        return numerator / 2
    }
    return divide()
}
areaOfTriangle(withBase: 3.0, andHeight: 5.0)

The function areaOfTriangle(withBase:andHeight:) takes two arguments of type Double: a base and a height. areaOfTriangle(withBase:andHeight:) ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.