我有两个变量,一个是可变数组,另一个是不可变数组。
let mutableArray = NSMutableArray(array: ["1","2","3"])
let immutableArray: NSArray = mutableArray但是,当我将元素附加到mutableArray时,immutableArray也会发生变化。
因此,我的假设是在.copy分配中使用immutableArray。但这是解决这个问题的最佳瓦里安吗?
发布于 2017-06-22 08:23:39
您应该使用Swift基础类型Array,它们在默认情况下是不可变的,而不是引用类型。
let numbers = [1, 2, 3] // type is: [Int]
let strings = numbers.map { $0.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等。如果要在map上使用NSArray,则需要将其转换为AnyObject,然后使用flatMap筛选出选项
let numbers = NSArray(array: [1, 2, 3])
let strings = numbers.map { ($0 as AnyObject).description }.flatMap { $0 }
print(strings) // ["1", "2", "3"]又丑又乱..。那么,为什么不立即使用Array呢?)
发布于 2017-06-22 08:24:18
你可以这样做
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)https://stackoverflow.com/questions/44693387
复制相似问题