closureのキャプチャーまわりの動きをplaygroundで確認していたところ、下記のような現象に遭遇しました。
var value: Int = 10
withUnsafePointer(to: &value) { print($0) } // 0x0000000116dabea0
let closure1 = {
withUnsafePointer(to: &value) { print($0) } // 0x0000000116dabea0
print("value = \(value)")
}
closure1() // value = 10 と表示
value = 20;
closure1() // value = 20 と表示 <- 値渡しになって"a = 10"になると思っていた
The Swift Programming Language (Swift3) Closureを見てみると
Closures can capture and store references to any constants and variables from the context in which they are defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you.
とのことなので、どんな定数でも変数でも参照がキャプチャされるということなのでしょうか。
value
をCapture Listに追加してみると...
let closure2 = { [value] in
print("value = \(value)")
}
closure2() // value = 20
value = 30
closure2() // value = 20
closure定義時のvalueが値渡しされているようです。