Swift - how to copy an array containing reference types

I am trying to copy an array and its values. Why do both arrays refer to the same variable? You can try this on the Playground.

var view = UIView()
view.tag = 1

var a = [UIView]()
var b = [UIView]()

a.append(view)

b = a
view.tag = 2

a[0].tag // value is 2
b[0].tag // value is 2?

      

+3


source to share


2 answers


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).



+3


source


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.

+2


source







All Articles