2017-07-31 27 views
0

我有這個簡單的結構。修改結構時,不能在不可變的值錯誤上使用變異成員

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,我得到的錯誤不能在一成不變的值使用可變成員:「部分」是一個「讓」常量

我該如何解決這個問題?

回答

2

通過在for定義的默認變量是let,他們不能被改變。所以,你必須使它成爲一個var. 容易的解決方案:

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

當您使用for循環時,該變量是一個let常量。 要解決它,你應該使用這個循環:

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

由於'struct'是一個值類型,您需要稍後使用您編輯的值更新數組:'sections [index] = section' –

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 
    } 
} 
1

當您的部分結構(價值型)部分變量是不可變的循環做。你不能直接修改它們的值。您必須創建每個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 
}) 
相關問題