gpt4 book ai didi

ios - Swift NSArray 突变

转载 作者:搜寻专家 更新时间:2023-11-01 07:11:27 34 4
gpt4 key购买 nike

我有两个变量,一个是可变数组,另一个是不可变的。

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 { $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(如上所做)、reduceflatMap , filter 等直接。如果你想在 NSArray 上使用 map,你需要转换为 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 呢? :)

关于ios - Swift NSArray 突变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44693387/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com