函数是可以嵌套的
当我们写一个比较长的函数的时候,我们可以使用函数嵌套的形式,将内部的代码抽取为一个嵌套的函数,这样看起来更加具有调理性
函数sumFunc就是嵌套在sumOneTwo函数中
- func sumOneTwo()->Int {
- var sum = 0
- func sumFunc(){
- sum = 1 + 2
- }
- sumFunc()
- return sum
- }
- print(sumOneTwo())
3
函数作为返回值
输出
- func threeTimes() -> ((Int)->Void) {
- func times(num:Int){
- print(num*3)
- }
- return times
- }
- let times = threeTimes()
- times(10)
30
作为函数的参数
输出
- func chose(numbers:[Int],condation:(Int)->Bool)->[Int]{
- var result = [Int]()
- for number in numbers {
- if condation(number) {
- result.append(number)
- }
- }
- return result
- }
- func biggerThanTen(number:Int)->Bool {
- if number > 10 {
- return true
- }
- return false
- }
- var numbers = [11,40,4,9,12]
- print(chose(numbers: numbers,condation: biggerThanTen))
[11,12]