可变状态上的 Swift 错误为 let const

问题描述 投票:0回答:1

我有简单的可编码 json 。我使用 for every 循环进行迭代,这里我根据 id 比较产品。如果 id 存在,那么它应该增加数量,否则添加该项目,我也在视图中使用这个函数..但是我收到以下错误..变异运算符的左侧不可变:“数量”是一个'let'常量我尝试在函数之前使用变异关键字也将结构let更改为var,但它没有帮助。

这是我的可编码 json ..

import Foundation

// MARK: - Welcome
struct ProductData: Codable, Hashable {
    let carts: [Cart]
}

// MARK: - Cart
struct Cart: Codable, Hashable {
    let id: Int
    let products: [Product]
}

// MARK: - Product
struct Product: Codable, Hashable, Identifiable {
    let id: Int
    let title: String
    let price, quantity, total: Int
    let discountPercentage: Double
    let discountedPrice: Int
    let thumbnail: String
}

这是我的功能..

class Order: ObservableObject {

    @Published var product = [Product]()
    @Published private(set) var productTotal: Int = 0

 func add(item: Product) {
           var exists = false
           product.forEach { product in
               if product.id == item.id {
                   exists = true
                   product.quantity += 1 // error on this line 
               }
           }
           if !exists {
               product.append(item)
           }
       }
    }

这是错误的屏幕截图。

swift swiftui codable hashable identifiable
1个回答
0
投票

您的

Product
具有
quantity
属性作为常量,您不能以这种方式修改它。将数量更改为
var
,然后使用 for 循环迭代产品数组。

struct Product: Codable, Hashable, Identifiable {
    ...
    var quantity: Int
}

class Order: ObservableObject {
    ...
    func add(item: Product) {
        var exists = false
        for i in 0..<product.count where product[i].id == item.id {
            product[i].quantity += 1
            exists = true
        }
        if !exists {
            product.append(item)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.