如何在SwiftUI的ForEach循环中修改变量属性?
问题解决:Cannot assign to property: 'newItem' is a 'let' constant
错误原因
- ForEach闭包中的参数
newItem默认是不可变的let常量,无法直接修改它的属性。 - 当前遍历的是传入的不可变数组
itemInfoList,即便能修改,也不会同步到你声明的可变数据源mutableItemInfoList,起不到修改数据的作用。
解决方案
提供两种可行的修改方式,按需选择:
方法1:使用绑定(推荐,需让模型实现Identifiable)
给itemInfo添加唯一标识,实现Identifiable协议,可直接通过绑定修改数组内的元素:
struct itemInfo: Identifiable, Hashable { let id = UUID() // 添加自动生成的唯一ID var item: Item var size: String var comment: String }
修改CheckoutView,遍历mutableItemInfoList的绑定版本:
struct CheckoutView: View { let itemInfoList: [itemInfo] @State private var mutableItemInfoList: [itemInfo] = [] @State private var showingAlert = false @State private var selectedSizesString = "" // 补充你用到的状态变量 init(itemInfoList: [itemInfo]) { self.itemInfoList = itemInfoList self._mutableItemInfoList = State(initialValue: itemInfoList) } var body: some View { ForEach($mutableItemInfoList) { $newItem in Button(action: { newItem.size = selectedSizesString showingAlert = true }) { Text("Print Selected Sizes") } .alert(isPresented: $showingAlert) { Alert( title: Text("Selected Sizes"), message: Text(selectedSizesString), dismissButton: .default(Text("OK")) ) } } } }
方法2:通过索引修改(无需修改模型)
如果不想修改itemInfo模型,可通过遍历数组索引定位元素并修改:
struct CheckoutView: View { let itemInfoList: [itemInfo] @State private var mutableItemInfoList: [itemInfo] = [] @State private var showingAlert = false @State private var selectedSizesString = "" init(itemInfoList: [itemInfo]) { self.itemInfoList = itemInfoList self._mutableItemInfoList = State(initialValue: itemInfoList) } var body: some View { ForEach(mutableItemInfoList.indices, id: \.self) { index in Button(action: { mutableItemInfoList[index].size = selectedSizesString showingAlert = true }) { Text("Print Selected Sizes") } .alert(isPresented: $showingAlert) { Alert( title: Text("Selected Sizes"), message: Text(selectedSizesString), dismissButton: .default(Text("OK")) ) } } } }
关键说明
- 必须操作
mutableItemInfoList这个@State变量,它是视图的可变数据源,修改后会触发视图刷新。 - 方法1的绑定方式更符合SwiftUI设计理念,代码更简洁;方法2适合临时场景,但要注意数组元素顺序变化时可能出现的索引错位问题。
内容的提问来源于stack exchange,提问作者anish1
相关产品推荐
相关产品推荐

