var list1 = [1, 2, 3, 4, 5]
var list2 = list1
list2.removeLast()
println(list1)
println(list2)
This is a simple code that just:
It seems that the assignment make something like copying but not assign the pointer.
I want to know if there is any official documents explain about it and how to make it enter code here
An array is a struct, and structs are value types, so they are copied by value and not by reference. The same happens for dictionaries, a copy is created if you assign to another variable.
Classes instead are reference types, and assignment copies the reference to the instance.
You can read more about that in Structures and Enumerations Are Value Types
Sidenote: a struct passed to a function is immutable - you cannot modify it within the function, unless you pass it by reference using the inout
attribute
Yes the Apple Swift documentation explains that Swift array (dictionary as well) is a struct, not an object and struct are copied when they are passed around in the code. If you create struct they are always copied. If you want to pass it by reference instead you should create class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With