Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
关于Swift&x27;闭包的价值捕获_Swift_Closures - Fatal编程技术网

关于Swift&x27;闭包的价值捕获

关于Swift&x27;闭包的价值捕获,swift,closures,Swift,Closures,我在读一本关于swift的书,偶然发现了这个截尾值捕获的例子 func makeStateMachine(maxState: Int) -> StateMachineType { var currentState: Int = 0 return { currentState++ if currentState > maxState { currentState = 0 } r

我在读一本关于swift的书,偶然发现了这个截尾值捕获的例子

func makeStateMachine(maxState: Int) -> StateMachineType { 
    var currentState: Int = 0

    return {
        currentState++
        if currentState > maxState {
            currentState = 0 
        }
        return currentState 
    }
} 

let bistate = makeStateMachine(1) 
println(bistate()); 
println(bistate()); 
println(bistate()); 
println(bistate());
输出应为“1 0 1 0”

我理解返回块在函数执行后如何捕获本地值“currentState”值,但为什么在下一次函数调用时不将该值设置回0? 这是因为双稳态常数的实例吗?或者是因为currentState在双状态初始化时使用值0初始化,并且编译器推断

var currentState: Int = 0

被忽略了吗?我对第一次通话后如何处理上述线路感到困惑。

这一点在以下章节的第一段中进行了解释:

闭包可以从定义它的周围上下文中捕获常量和变量。然后,闭包可以从其主体中引用和修改这些常量和变量的值,即使定义常量和变量的原始范围已不存在

在下面的几段注释中:

Swift确定应通过引用捕获的内容以及应通过值复制的内容


因此,闭包获取
currentState
的引用(而不是副本)。闭包内对该变量的任何更改都是在闭包外定义的实例中完成的,即使作用域不再存在(因为执行了
makeStateMachine
函数)。

该书的作者:-)

是的,我可以确认你的评论是正确的,函数返回一个闭包。我添加了一些评论,希望能澄清一些问题:

func makeStateMachine(maxState: Int) -> StateMachineType { 
    // this variable is initialised when makeStateMachien is invoked
    var currentState: Int = 0

    // the function returns this closure
    return {
        // by using 'currentState' this variable is captured
        currentState++
        if currentState > maxState {
            currentState = 0 
        }
        return currentState 
    }
} 
调用此函数时:

let bistate = makeStateMachine(1) 

常量
bistate
现在保存对
makeStateMachine
返回的闭包的引用

似乎没有人解释过


函数
makeStateMachine
返回一个包含两个变量的闭包:
maxState
currentState
。当使用
1
maxState
调用时,返回的闭包将递增
currentState
,将其与
1
进行比较,然后在超出
1
时将
currentState
重置为
0
。给定对返回闭包的多个调用,返回值的顺序是
1,0,1,0,…
。更一般地说,对于任何
maxState
来说,顺序是
1,…,maxState,0,…,maxState,…

我想我已经弄明白了,但是有人能确认吗?是因为函数返回闭包本身,而不是函数的全部?这对于闭包如何仍然保留函数中定义的局部变量更有意义。