gpt4 book ai didi

arrays - 选择要附加到三元运算符 'if' 运算符 : "Immutable value... only has mutating members" 的数组

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:47 25 4
gpt4 key购买 nike

我有两个数组:

var addedToIgnoreList: [String] = []
var removedFromIgnoreList: [String] = []

我想将一个值附加到这些数组之一。如果我这样做:

(isUserIgnored ? removedFromIgnoreList : addedToIgnoreList).append("username")

我得到 Immutable value of type '[String]' only has mutating members named 'append'

如果我使用中间变量,它会起作用:

var which = isUserIgnored ? removedFromIgnoreList : addedToIgnoreList
which.append("username")

使用额外变量是唯一的方法吗?


更新:额外的变量将无法正常工作,因此 if 语句是唯一的选择。请参阅接受的答案以获取解释。

最佳答案

这都与数组是值类型有关,而不是引用类型。也就是说,变量不指向数组(不像 NSArray)。它们数组,将数组分配给新变量会生成一个新副本。

您收到该错误的原因是该语句:

(isUserIgnored ? removedFromIgnoreList : addedToIgnoreList).append(etc)

制作两个数组之一的临时副本,并且正在对该副本进行append 调用。该副本将是不可变的——这是一件好事,因为如果不是,你可能会无意中改变它(正如你在这里尝试的那样),结果却发现没有发生任何变化——你的副本被制作、变异,然后丢弃。

请记住:

var which = isUserIgnored ? removedFromIgnoreList : addedToIgnoreList
which.append("username")

制作副本。所以改变 which 不会改变任何一个原始数组。

更改数组本身最直接的方法是使用 if 语句:

if isUserIgnored {
removedFromIgnoreList.append("username")
}
else {
addedToIgnoreList.append("username")
}

这不会复制,而是就地修改数组。

另一方面,如果您想要一个附加了值的新数组,最简单的方法可能是使用 + 运算符:

let newCopy =  (isUserIgnored ? removedFromIgnoreList : addedToIgnoreList) + ["username"]

关于arrays - 选择要附加到三元运算符 'if' 运算符 : "Immutable value... only has mutating members" 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753014/

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