swift 允许使用 copy() 或 unshare 方法()
swift enable to use copy() or unshare method()
在我的第一个 Swift 项目中,我尝试复制一个数组及其对海关对象的引用。经过多次研究,我意识到最好的方法是使用 copy() 或 unshare()。
但就我而言,此方法不存在!
例如,我声明变量数据:
var datas:Array<ChartColor> = [ChartColor]();
(ChartColor 是自定义 class 扩展 NSObject)
但是如果我尝试将数据复制到另一个数组中,就像这样:
var datasCopied:Array<ChartColor> = self.datas.copy();
copy() 方法不存在,出现编译器错误:
'Array' 没有名为 'copy'
的成员
我的xCode版本是6.2(6C131e)
我的情况如何复制?
如果您在 Swift 中查找数组定义(按住 Cmd 并单击),您将看到 swift 中的数组本质上是 struct
的,并且:
Structures and Enumerations Are Value Types
A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.
...因此,对于复制数组,一个简单的赋值就足够了。
例如:
var source = [1, 2, 3]
var destination = source // Copy
source[0] = 10
source // [10, 2, 3]
destination // [1, 2, 3]
在我的第一个 Swift 项目中,我尝试复制一个数组及其对海关对象的引用。经过多次研究,我意识到最好的方法是使用 copy() 或 unshare()。 但就我而言,此方法不存在!
例如,我声明变量数据:
var datas:Array<ChartColor> = [ChartColor]();
(ChartColor 是自定义 class 扩展 NSObject)
但是如果我尝试将数据复制到另一个数组中,就像这样:
var datasCopied:Array<ChartColor> = self.datas.copy();
copy() 方法不存在,出现编译器错误:
'Array' 没有名为 'copy'
的成员我的xCode版本是6.2(6C131e)
我的情况如何复制?
如果您在 Swift 中查找数组定义(按住 Cmd 并单击),您将看到 swift 中的数组本质上是 struct
的,并且:
Structures and Enumerations Are Value Types
A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.
...因此,对于复制数组,一个简单的赋值就足够了。
例如:
var source = [1, 2, 3]
var destination = source // Copy
source[0] = 10
source // [10, 2, 3]
destination // [1, 2, 3]