代码之家  ›  专栏  ›  技术社区  ›  Isuru PapaSmurf

修改结构时,无法对不可变值错误使用突变成员

  •  7
  • Isuru PapaSmurf  · 技术社区  · 9 年前

    我有一个简单的结构。

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

    在VC中,我声明了一个数组 Section 在顶端,就像这样, fileprivate var sections: [Section] = [] .我补充了一些 中的对象 viewDidLoad() .

    稍后,我需要删除一些 Offer 来自 offers 部分 s

    我遍历 sections 包含 这需要删除。

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

    但是当我试图删除那个特定的 从 数组,我得到错误 无法对不可变值使用变异成员:“section”是“let”常量 .

    我该如何解决这个问题?

    4 回复  |  直到 9 年前
        1
  •  14
  •   Crashalot    9 年前

    默认情况下,在 for 是 let 它们不能被改变。所以你必须让它成为 var.

    for var section in sections {
        if let i = section.offers.index(where: { $0.id == offer.id }) {
            section.offers.remove(at: i)
        }
    }
    
        2
  •  5
  •   Duyen-Hoa    9 年前

    结构(值类型) 变量是不可变的。不能直接修改其值。您必须创建每个截面对象的可变版本,进行修改并重新分配给数组(在右侧索引处替换修改后的对象)。例如:

    sections = sections.map({
        var section = $0
        if let i = section.offers.index(where: { $0.id == offer.id }) {
            section.offers.remove(at: i)
        }
        return section
    })
    
        3
  •  0
  •   dip    9 年前

    自引用对象打开以来

    你也是 使用值类型(结构)

    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
        }
    }
    
        4
  •  0
  •   Sirop4ik    5 年前

    当您使用 for 循环,变量为 let 常数 要修复它,您应该使用以下循环:

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