Defining and using nested functions

In Swift, it is possible to define functions inside other functions. In other words, we can nest functions inside other functions. Nested functions are only accessible inside their enclosing functions and are hidden from the outside world by default. The enclosing function can return the nested function in order to allow the nested function to be used in other scopes. The following example presents a function that contains two nested functions and returns one of them according to the value of its isPlus parameter:

func choosePlusMinus(isPlus: Bool) -> (Int, Int) -> Int {
    func plus(a: Int, b: Int) -> Int {
        return a + b
    }
    func minus(a: Int, b: Int) -> Int {
        return a - b
    }
    return isPlus ? plus : minus
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset