簡體   English   中英

關於Swift在閉包上的價值捕獲

[英]Regarding Swift's value capture on closures

我正在讀一本關於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? 是因為bistate常數的實例? 或者是因為currentState在bistate初始化時初始化為值0,編譯器推斷出

var currentState: Int = 0

被忽略了? 我對第一次通話后如何處理上述行感到困惑。

這在Capturing Values的第一段中有解釋:

閉包可以從定義它的周圍上下文中捕獲常量和變量。 然后閉包可以引用並修改其體內的常量和變量的值,即使定義常量和變量的原始范圍不再存在。

並在下面的幾段中注明:

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返回一個捕獲兩個變量的閉包: maxStatecurrentState maxState1時調用,返回的閉包將增加currentState ,將其與1進行比較,然后在超過1currentState重置為0 給定對返回閉包的多次調用,返回值的序列是1, 0, 1, 0, ... 更一般地說,對於任何maxState ,序列是1, ..., maxState, 0, ..., maxState, ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM