斯威夫特 - 如何使一个数组的精确副本? [英] Swift - How do I make a exact duplicate copy of an array?

查看:117
本文介绍了斯威夫特 - 如何使一个数组的精确副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SWIFT语言的初学者。

我怎么会让一个数组完全相同的副本?
我有很难找到关于复制斯威夫特的阵列信息。请帮助!

我试着用.copy()

  VAR originalArray = [1,2,3,4]
VAR duplicateArray = originalArray.copy()


解决方案

阵列在斯威夫特完全值语义,所以没有必要进行任何幻想。

VAR duplicateArray = originalArray 是你所需要的。


如果您的数组中的内容是引用类型,那么是的,这只会指针复制到你的对象。要执行内容的深层副本,你会改用地图并执行每个实例的副本。对于符合 NSCopying 协议基础类,你可以使用复制()方法:

 令x = [NSMutableArray的(),NSMutableArray的(),NSMutableArray的()]
让Y = X
令z = x.map {$ 0.copy()}X [0] === Y [0] //真
X [0] === Z [0] //假

请注意,这里也有陷阱是斯威夫特的值语义都在努力保护你的 - 例如,因为的NSArray 重新presents一个不变的阵列,它的复制方法仅返回到自身的引用,所以测试上面会产生意想不到的效果。

I am a beginner in SWIFT language.

How would I make an exact duplicate of an array? I am having hard time finding information about duplicating an array in swift. Please help!

I tried using .copy()

var originalArray = [1, 2, 3, 4]
var duplicateArray = originalArray.copy()

解决方案

Arrays have full value semantics in Swift, so there's no need for anything fancy.

var duplicateArray = originalArray is all you need.


If the contents of your array are a reference type, then yes, this will only copy the pointers to your objects. To perform a deep copy of the contents, you would instead use map and perform a copy of each instance. For Foundation classes that conform to the NSCopying protocol, you can use the copy() method:

let x = [NSMutableArray(), NSMutableArray(), NSMutableArray()]
let y = x
let z = x.map { $0.copy() }

x[0] === y[0]   // true
x[0] === z[0]   // false

Note that there are pitfalls here that Swift's value semantics are working to protect you from—for example, since NSArray represents an immutable array, its copy method just returns a reference to itself, so the test above would yield unexpected results.

这篇关于斯威夫特 - 如何使一个数组的精确副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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