Swift-如何复制包含引用类型的数组 [英] Swift - How to copy an array that contains reference types

查看:107
本文介绍了Swift-如何复制包含引用类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试复制数组及其值。为什么两个数组都引用相同的变量?您可以在Playground中进行尝试。

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?


推荐答案

在Swift中,数组的值类型是复制它会创建一个单独的副本。但是由于UIView是引用类型,并且您的数组包含UIView,因此在复制时它们指向相同的内存位置或相同的引用。您的数组 a b 即使两个单独的数组且每个包含一个对象,它们也会指向相同的位置。将标签号分配为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).

这篇关于Swift-如何复制包含引用类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆