Swift - how to copy an array containing reference types
Since Array in Swift has value types, copying creates a separate copy. But since UIViews have reference types and your array contains UIViews, when copied, they point to the same location in memory or to the same reference. Your array, a
and b
although the two separate arrays contain one object each, they will point to the same location. As long as you assign the tag number as 2, it just overrides the old number in that memory location (reference).
source to share
If you have a copy function UIView
that you need, just usemap
var a = [UIView]()
var b = map (a) { $0.copyTheView() }
In your case, the arrays a
and b
, while they are different, point to the same views. Thus, if you change one of the links in a
, your variable view
, then the link in b
will also see the change.
source to share