如何在 Swift 中创建不可变数组?
粗浅地阅读文档会建议您可以这样做
let myArray = [1,2,3]
但遗憾的是,这实际上产生了一个可变的、固定大小的数组。这种可变性造成了常见的谜题,其中包含意想不到的别名和函数改变它们的参数:
let outterArray = [myArray, myArray]
outterArray[0][0] = 2000
outterArray //=> [[2000,2,3],[2000,2,3]] surprise!
func notReallyPure(arr:Int[]) -> () { arr[0] = 3000 }
notReallyPure(myArray)
myArray // => [3000,2,3]
并不比 C 好多少。
如果我想要不变性,最好的选择是将它包装在 NSArray
中,如下所示:
let immutableArray = NSArray(myArray: [1,2,3])
这看起来很疯狂。我在这里缺少什么?
更新(2015-07-26):
这个问题可以追溯到 Swift 的早期。从那时起,Swift 已经更新,因此不可变数组实际上是不可变的,如下面的答案所示。
最佳答案
这在 Xcode 6 beta 3 中发生了变化。正如您所描述的,数组过去是半可变的,其元素可变但长度固定,但现在不可变数组与字典共享相同的值语义:
来自 Xcode 6 beta 3 发行说明:
• Array in Swift has been completely redesigned to have full value semantics like Dictionary and String have always had in Swift. This resolves various mutability problems – now a 'let' array is completely immutable, and a 'var' array is completely mutable – composes properly with Dictionary and String, and solves other deeper problems. Value semantics may be surprising if you are used to NSArray or C arrays: a copy of the array now produces a full and independent copy of all of the elements using an efficient lazy copy implementation. This is a major change for Array, and there are still some performance issues to be addressed. Please !see the Swift Programming Language for more information. (17192555)
Swift 书中关于数组的原始信息已于 2014 年 7 月 7 日更新,以反射(reflect) beta 3 的变化。 (如果您像我一样在 Mac 上使用 iBooks,您可能需要删除并重新下载它才能获取 7 月 7 日的更新——我无法让它自动更新。)
关于arrays - 如何在 Swift 中创建不可变数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090741/