修改结构时,不能在不可变的值错误上使用变异成员

问题描述:

我有这个简单的结构。修改结构时,不能在不可变的值错误上使用变异成员

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

在VC,我已经宣布在像这样,fileprivate var sections: [Section] = []顶端这些Section S的阵列。我在viewDidLoad()中添加了一些Section对象。

后来,我需要从offers数组中删除一些Offer对象,其中一些Section s。

我遍历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 
    } 
} 

但是,当我尝试从offers数组中删除特定Offer,我得到的错误不能在一成不变的值使用可变成员:“部分”是一个“让”常量

我该如何解决这个问题?

通过在for定义的默认变量是let,他们不能被改变。所以,你必须使它成为一个var. 容易的解决方案:

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

当您使用for循环时,该变量是一个let常量。 要解决它,你应该使用这个循环:

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

由于'struct'是一个值类型,您需要稍后使用您编辑的值更新数组:'sections [index] = section' –

由于参考对象上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 
    } 
} 

当您的部分结构(价值型)部分变量是不可变的循环做。你不能直接修改它们的值。您必须创建每个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 
})