LoginSignup
11
5

More than 5 years have passed since last update.

【Swift】closureでstructがキャプチャーされるときに参照になっていた

Last updated at Posted at 2016-10-26

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が値渡しされているようです。

11
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5