如何制作数组的精确副本? [英] How do I make a exact duplicate copy of an array?

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

问题描述

如何制作一个数组的精确副本?

How would I make an exact duplicate of an array?

我很难找到有关在 Swift 中复制数组的信息.

I am having hard time finding information about duplicating an array in Swift.

我尝试使用 .copy()

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

推荐答案

数组在 Swift 中具有完整的值语义,因此不需要任何花哨的东西.

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

var duplicateArray = originalArray 就是你所需要的.

如果数组的内容是引用类型,那么是的,这只会复制指向对象的指针.要执行内容的深层复制,您可以使用 map 并执行每个实例的复制.对于符合NSCopying协议的Foundation类,可以使用copy()方法:

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

注意这里有一些陷阱,Swift 的值语义正在努力保护你免受 - 例如,由于 NSArray 表示一个不可变的数组,它的 copy 方法只返回一个引用自身,所以上面的测试会产生意想不到的结果.

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天全站免登陆