修改结构时不能对不可变值错误使用变异成员

Isu*_*uru 7 arrays struct ios swift

我有这个简单的结构。

struct Section {
    let store: Store
    var offers: [Offer]
}
Run Code Online (Sandbox Code Playgroud)

在 VC 中,我Section像这样在顶部声明了这些s的数组,fileprivate var sections: [Section] = []. 我SectionviewDidLoad().

后来,我需要Offeroffers一些Sections内的数组中删除一些对象。

我遍历sections数组以找到Section包含Offer需要删除的 。

for section in sections {
    if let i = section.offers.index(where: { $0.id == offer.id }) {
        section.offers.remove(at: i) // Cannot use mutating member on immutable value: 'section' is a 'let' constant
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试Offeroffers数组中删除该特定内容时,出现错误Cannot use mutating member on immutable value: 'section' is a 'let' constant

我该如何解决?

Whi*_*dow 13

默认情况下,定义在forare 中的变量let不能更改。所以你必须使它成为一个var. 更简单的解决方案:

for var section in sections {
    if let i = section.offers.index(where: { $0.id == offer.id }) {
        section.offers.remove(at: i)
    }
}
Run Code Online (Sandbox Code Playgroud)


Duy*_*Hoa 8

当您执行节结构(值类型)的 for 循环时,变量是不可变的。您不能直接修改它们的值。您必须创建每个Section对象的可变版本,进行修改并分配回数组(在正确的索引处替换修改后的对象)。例如:

sections = sections.map({
    var section = $0
    if let i = section.offers.index(where: { $0.id == offer.id }) {
        section.offers.remove(at: i)
    }
    return section
})
Run Code Online (Sandbox Code Playgroud)