修改结构体时出现无法在不可变值上使用可变成员的错误。

10

我有一个简单的结构体。

struct Section {
    let store: Store
    var offers: [Offer]
}

在VC中,我在顶部声明了一个这些Section的数组,像这样:fileprivate var sections: [Section] = []。并且我在viewDidLoad()中添加一些Section对象。
稍后,我需要从某些Section内的offers数组中删除一些Offer对象。
我遍历sections数组来找到包含需要删除OfferSection
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
    }
}

但是当我尝试从offers数组中删除特定的Offer时,我会收到错误信息Cannot use mutating member on immutable value: 'section' is a 'let' constant。

我该如何解决这个问题呢?

4个回答

17

默认情况下,在 for 循环中定义的变量是 let 类型的,不能被更改。因此,您需要将其设为 var

更简单的解决方案:

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

8

当您对sections结构体(值类型)执行for循环时,section变量是不可变的。您不能直接修改它们的值。您需要创建每个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
})

0

当您使用 for 循环时,变量是一个 let 常量。 要修复它,您应该使用以下循环:

for index in 0..<sections.count {
    var section = sections[index]
    [...]
}

3
因为struct是值类型,所以您需要稍后使用编辑过的值更新数组:sections[index] = section - mag_zbc

0

由于For循环中的引用对象是不可变的,因此您必须创建一个中间变量来进行逻辑操作。

另外,如果您正在使用值类型(结构),则在完成后必须从中间变量更新数据源。

for j in 0 ..< sections.count {

    var section = sections[j]

    if let i = section.offers.index(where: { $0.id == offer.id }) {

        aSection.offers.remove(at: i) // Cannot use mutating member on immutable value: 'section' is a 'let' constant
        sections[j] = section
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接