How to use nested functions in Swift

1 Answer

0 votes
func selectfunction(minus: Bool) -> (Int) -> Int {
    func plusf(x: Int) -> Int { return x + 1 }
    func minusf(x: Int) -> Int { return x - 1 }
    return minus ? minusf : plusf
}
let selectedminusf = selectfunction(minus: true)

var n = 5
while n != 0 {
    print(n)
    n = selectedminusf(n)
}



  
/*
run:
  
5
4
3
2
1
  
*/

 



answered Feb 12, 2021 by avibootz
...