LoginSignup
0
0

More than 1 year has passed since last update.

[Swift] Proof of CoW

Posted at

Swift has two kinds of type, Value types and Reference types. Value types will copy the data when assign to another variable. But for array it does not copy every time, it use Copy-on-Write.

import Foundation

var a = [1,2,3,4,5,6]
var b = a

func address(_ p: UnsafeRawPointer) {
    print(p)
}

address(a)
address(b)

a.append(6)

address(a)
address(b)
0x0000000110412210
0x0000000110412210
0x0000000110412980
0x0000000110412210

See the above example, a and b will point to same memory address, var b = a dose not have copy occurred. When you change the content of a, it will copy the data and assign the new data address to a.

0
0
0

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
0
0