【发布时间】:2020-12-22 06:38:20
【问题描述】:
今天我在ForEachSwiftUI 上遇到问题。
我有几个来自不同商店的产品列表,问题是当我按下其中一个按钮来增加或减少库存时,我需要修改库存。但是当我真的尝试这样做时,我遇到了以下错误:
Left side of mutating operator isn't mutable: 'product' is a 'let' constant SwiftUI
我不知道如何让它发挥作用,我是来听听一些建议的
@State var shoppingCartList : [Product]
ForEach(productsByStore(storeId: store.id), id: \.self){product in
VStack(alignment: .leading, spacing: 0){
HStack{
Group{
HStack{
HStack{
Button(action: {
if (product.quantity > 1){ // error here: product.quantity -= 1
}
}){
Text("—")
.multilineTextAlignment(.center)
}
.padding([.leading], 5)
Text(String(product.quantity))
Button(action: {
if product.quantity < product.stock!{
// error here: product.quantity += 1
}
}){
Text("+")
.multilineTextAlignment(.center)
}
}
Spacer()
Text("available: " + String(describing: product.stock!))
}
}
}
}
Divider()
}
Spacer()
}
func productsByStore(storeId: Int) ->[Product] {
return shoppingCartList.filter{$0.storeId == storeId}
}
附言。 productsByStore()根据店铺返回商品列表
PS2。 product.stock 是库存中可用商品的数量,product.quantity 是用户可以选择的商品数量。
例如:Palm One -> 数量 = 4。库存 = 10
我可以使用按钮(+ 和 -)添加或删除手掌的数量
PS3。产品结构
struct Product: Hashable, Codable{
var name: String
var quantity: Int
var stock: Int?
var storeId: Int
init(from decoder: Decoder) throws{
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
quantity = try container.decodeIfPresent(Int.self, forKey: .quantity) ?? 0
stock = try container.decodeIfPresent(Int?.self, forKey: .stock) ?? 0
storeId = try container.decodeIfPresent(Int.self, forKey: .storeId) ?? 0
}
private enum CodingKeys: String, CodingKey{
case name = "Nombre"
case quantity = "Cantidad"
case stock = "Stock"
case storeId = "IdStore"
}
init(name: String, quantity: Int, stock: Int?, storeId: Int ){
self.name = name
self.quantity = quantity
self.stock = stock
self.storeId = storeId
}
}
【问题讨论】:
-
产品是如何定义的?
-
我更新问题
-
产品将有:名称数量库存
-
请显示数据类型的实际声明。此外,错误显示
currentProduct...那是什么? -
对不起!我改了名字
标签: swiftui swiftui-list