struct Array
are value types in Swift, which means that they are always copied when assigning to another variable. However, each struct Array
contains pointers (not displayed in the public interface) for storing elements. Therefore after
var a = [1, 2, 3, 4] var b = a
both a
and b
are (formally independent) values, but with pointers to the same element store. Only when one of them is mutated is a copy of the element store created. This is called βcopy on writeβ and, for example, is explained in
So after
b[0] = 17
a
and b
are values ββwith pointers to different (independent) repositories of elements. A further mutation of b
does not copy the element store again (unless b
is copied to another variable). Finally, if you assigned the value back
a = b
the old repository of elements a
freed, and both values ββare again pointers to the same repository.
Therefore, in your example:
var y = propertyWithLongDescriptiveName
a copy of the element store is made exactly once (provided that you do not copy y
into an additional variable).
If the size of the array does not change, then a possible approach might be
var propertyWithLongDescriptiveName = [1.0, 2.0, 3.0, 4.0] propertyWithLongDescriptiveName.withUnsafeMutableBufferPointer { y in
withUnsafeMutableBufferPointer()
causes a closure using UnsafeMutableBufferPointer
in the element store. A UnsafeMutableBufferPointer
is a RandomAccessCollection
and therefore offers a massive interface.