You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI报错:无法对不可变值使用可变成员,'shop'为let常量

问题:无法向Shop的container中添加Product

问题原因

  • 你在ForEach(shops)中获取到的shop是原数组元素的值拷贝,不是对@State数组里元素的直接引用。修改这个拷贝的container,根本不会影响原数组里的Shop对象。
  • 就算shops声明为var,但修改拷贝对象的操作无法让SwiftUI感知到@State数组的变化,自然不会触发视图更新。

解决方案

要修改原@State数组里的对应Shop元素,需要通过绑定直接操作原数组中的对象,让SwiftUI能感知到变化并更新视图。

以下是修改后的完整代码:

import SwiftUI

struct Shop: Identifiable {
    let name: String
    var container: [Product]
    var id = UUID()
}

struct Product: Identifiable {
    let name: String
    var id = UUID()
}

struct ContentView: View {
    
    @State var shops: [Shop] = [
        Shop(name: "Apple Store", container: []),
        Shop(name: "StopShop", container: [Product(name: "milk")])
    ]
    
    var body: some View {
        NavigationView {
            List {
                // 使用绑定式ForEach,直接获取原数组元素的引用
                ForEach($shops) { $shop in
                    NavigationLink(shop.name, destination: {
                        List {
                            ForEach(shop.container) { product in
                                Text(product.name)
                            }
                        }
                        .navigationBarTitle(shop.name)
                        .navigationBarItems(trailing: Button {
                            // 通过绑定直接修改原数组中的Shop元素
                            $shop.container.append(Product(name: "Cheese"))
                        } label: {
                            Text("add").bold()
                        })
                    })
                }
            }
            .navigationBarTitle("Shops")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

关键修改说明

  • 将ForEach(shops)替换为ForEach($shops),这样拿到的是Shop的绑定值$shop,直接修改$shop.container会同步更新原@State数组内的元素。
  • SwiftUI会自动检测@State数组的变化,触发视图刷新,添加的Product就能正常显示了。

内容的提问来源于stack exchange,提问作者Erik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 02:31:01