O'Reilly logo

Swift Functional Programming - Second Edition by Dr. Fatih Nayebi

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

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 ...

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