- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 130字
- 2021-07-02 23:54:32
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
}