swift学习记录(函数--嵌套函数)

来源:互联网 发布:创维电视有线网络连接 编辑:程序博客网 时间:2024/04/30 02:17

嵌套函数

定义在函数体中的函数,称为嵌套函数(nested functions)。

默认情况下,嵌套函数是对外是不可见的,但可以被封闭他们的函数(enclosing function)调用。封闭函数可以返回它的一个嵌套函数,使这个函数在其他域中可以被使用。

分析一段代码

<span style="font-size:14px;">func chooseStep(step : Bool)->(Int)->String{        func stepForward(input : Int)->String{           return String(input+2)    }    func stepBackward(input :Int) ->String{        return String(input-2)    }    return step ? stepBackward : stepForward}</span>

定义函数 chooseStep ,有一个Bool型的参数 step  他的返回值类型 为 ->(Int)->String 

函数体内 包含了两个函数 stepForward 和 stepBackward

return 语句是一个 三木运算,step 为 true 时返回 setpBackward函数 ;step 为 false 时 返回 stepForward

接下来调用这个函数

<span style="font-size:14px;">var currentValue = 3let next = chooseStep(currentValue>0)</span>
当我们调用函数 chooseStep 的时候返回的不一个具体的值,而是一个函数的指针,这个指针指向了常量 next。所以说,next 是个函数。具体是哪个函数呢?

在我们调用的chooseStep函数的时候,传入(currentValue > 0)3 > 0 为 true 。返回的是stepBackward这个函数的指针,所以next 就相当于是 stepBackward 函数。

接下来调用 next 函数

<span style="font-size:14px;">var nextValue = next(currentValue)print(nextValue)//1</span>

现在调用 next 函数,就是在调用 stepBackward 函数,参数为 Int ,返回值为String 

回头再来看chooseStep 函数 ,他的返回值类型 。->(Int)->String  这里的Int 就是 嵌套函数 的参数类型。String就是 嵌套函数的返回值类型

0 0
原创粉丝点击