问题描述:

I am trying to copy an array and its values. Why are both arrays referencing the same variable? You can try this in 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?

网友答案:

Since Array's in Swift are of value types, when you copy it will create a separate copy. But since UIView is of reference types and your array contains UIViews, while copying they are pointing to same memory location or same reference. Your Array a and b even though two separate array's and contains one object each, they will point to same location. While you are assigning the tag number as 2, it just overriding the old number at that memory location(reference).

网友答案:

If you have a function to copy a UIView, which you will need, then just use map

var a = [UIView]()
var b = map (a) { $0.copyTheView() }

In your case, arrays a and b, while themselves distinct, point to the same views. Thus if you modify one of the references in a, your variable view, then the reference in b will also see the modification.

相关阅读:
Top