简体   繁体   English

Swift - 如何复制包含引用类型的数组

[英]Swift - How to copy an array that contains reference types

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. 由于Swift中的Array是值类型,因此当您复制它时将创建一个单独的副本。 But since UIView is of reference types and your array contains UIViews, while copying they are pointing to same memory location or same reference. 但由于UIView是引用类型而您的数组包含UIViews,因此复制时它们指向相同的内存位置或相同的引用。 Your Array a and b even though two separate array's and contains one object each, they will point to same location. 您的数组ab即使是两个单独的数组并且每个包含一个对象,它们也将指向相同的位置。 While you are assigning the tag number as 2, it just overriding the old number at that memory location(reference). 当您将标签号分配为2时,它只是覆盖该内存位置的旧号码(参考)。

If you have a function to copy a UIView , which you will need, then just use map 如果你有一个复制你需要的UIView的功能,那么只需使用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. 在您的情况下,数组ab虽然本身不​​同,但指向相同的视图。 Thus if you modify one of the references in a , your variable view , then the reference in b will also see the modification. 因此,如果您修改a ,变量view中的a引用,那么b的引用也将看到修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM