O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 areaOfTriangleWith(base: Double, height: Double) -> Double {
    let numerator = base * height
    func divide() -> Double {
        return numerator / 2
    }
    return divide()
}
areaOfTriangleWith(base: 3.0, height: 5.0)

The function areaOfTriangleWith(base:height:) takes two arguments of type Double: a base and a height. It also returns a Double. Inside ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required