我有這個簡單的結構。修改結構時,不能在不可變的值錯誤上使用變異成員
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
,我得到的錯誤不能在一成不變的值使用可變成員:「部分」是一個「讓」常量。
我該如何解決這個問題?
由於'struct'是一個值類型,您需要稍後使用您編輯的值更新數組:'sections [index] = section' –