Swift NSArray 突变
Swift NSArray mutation
我有两个变量,一个是可变数组,另一个是不可变的。
let mutableArray = NSMutableArray(array: ["1","2","3"])
let immutableArray: NSArray = mutableArray
但是当我将元素追加到 mutableArray
时,我的 immutableArray
也在改变。
所以我的假设是在 immutableArray
分配中使用 .copy
。但它是解决问题的最佳变量吗?
您应该使用 Swift 基础类型 Array
,它们默认是不可变的,并且是值类型而不是引用类型。
let numbers = [1, 2, 3] // type is: [Int]
let strings = numbers.map { [=10=].description } // type is: [String]
print(strings) // ["1", "2", "3"]
// THIS DOES NOT COMPILE
strings.append("foo") //Compilation error: cannot use mutating member on immultable value `strings` is a `let` constant
// Instead, super easily, declare a mutable copy just by this line
var mutableStrings = strings // since `Array` is value type, this only copies values over
mutableStrings.append("foo")
print(mutableStrings) // ["1", "2", "3", "foo"]
或者您是否出于某些特殊原因需要 NSArray?
使用Array
有很多优点,使用可以直接使用map
(如上),reduce
,flatMap
,filter
等。如果你想在 NSArray
上使用 map
,你需要转换为 AnyObject
,然后使用 flatMap
:
过滤掉可选项
let numbers = NSArray(array: [1, 2, 3])
let strings = numbers.map { ([=11=] as AnyObject).description }.flatMap { [=11=] }
print(strings) // ["1", "2", "3"]
这又丑又乱...那么为什么不立即使用 Array
呢? :)
你可以这样做
let mutableArray = NSMutableArray(array: ["1","2","3"])
let immutableArray: NSArray = NSArray(array: mutableArray)
mutableArray.add("4")
print(mutableArray) // (1,2,3,4)
print(immutableArray) // (1,2,3)
我有两个变量,一个是可变数组,另一个是不可变的。
let mutableArray = NSMutableArray(array: ["1","2","3"])
let immutableArray: NSArray = mutableArray
但是当我将元素追加到 mutableArray
时,我的 immutableArray
也在改变。
所以我的假设是在 immutableArray
分配中使用 .copy
。但它是解决问题的最佳变量吗?
您应该使用 Swift 基础类型 Array
,它们默认是不可变的,并且是值类型而不是引用类型。
let numbers = [1, 2, 3] // type is: [Int]
let strings = numbers.map { [=10=].description } // type is: [String]
print(strings) // ["1", "2", "3"]
// THIS DOES NOT COMPILE
strings.append("foo") //Compilation error: cannot use mutating member on immultable value `strings` is a `let` constant
// Instead, super easily, declare a mutable copy just by this line
var mutableStrings = strings // since `Array` is value type, this only copies values over
mutableStrings.append("foo")
print(mutableStrings) // ["1", "2", "3", "foo"]
或者您是否出于某些特殊原因需要 NSArray?
使用Array
有很多优点,使用可以直接使用map
(如上),reduce
,flatMap
,filter
等。如果你想在 NSArray
上使用 map
,你需要转换为 AnyObject
,然后使用 flatMap
:
let numbers = NSArray(array: [1, 2, 3])
let strings = numbers.map { ([=11=] as AnyObject).description }.flatMap { [=11=] }
print(strings) // ["1", "2", "3"]
这又丑又乱...那么为什么不立即使用 Array
呢? :)
你可以这样做
let mutableArray = NSMutableArray(array: ["1","2","3"])
let immutableArray: NSArray = NSArray(array: mutableArray)
mutableArray.add("4")
print(mutableArray) // (1,2,3,4)
print(immutableArray) // (1,2,3)