Swift - Function Nested Functions

Introduction

You can define functions within a function: this is known as nested functions.

A nested function can only be called within the function in which it is defined.

The functionBuilder() function shown in the previous section can be rewritten using nested functions:

func functionBuilder(function:Int) -> (Int, Int)->Int {
    func sum(num1: Int, num2: Int) -> Int {
       return num1 + num2
    }

    func diff(num1: Int, num2: Int) -> Int {
       return abs (num1 - num2)
    }
    if function == 0 {
       return sum
    } else {
       return diff
    }
}

Related Topic