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
.