更新时间:2023-01-17 09:14:55
为了在这样的循环中更轻松地进行修改,您应该将Products
设为一个类,因为它是通过引用传递的.另外,在Products
中将quantities
更改为var
,并将解析代码替换为此:
For easier modification in loops like this, you should make Products
a class, since it's passed by reference. Also, make quantities
to a var
in your Products
and replace the parsing code to this:
for product in products.arrayValue {
let productId = product["product_id"].stringValue
let quantity = (sizeId: product["size_id"].stringValue,
quantity: product["quantity"].stringValue)
if let product = self.productWithQuantites.filter({ $0.id == productId }).first {
product.quantities?.append(quantity)
} else {
self.productWithQuantites.append(Products(id: productId, quantities: [quantity]))
}
}
此代码将新的元组附加到现有产品的quantities
属性,或者如果不存在,则创建新的Products
并将其附加到productWithQuantites
.
This code appends a new tuple to the quantities
property of an existing product, or if it does not exist, it creates a new Products
and appends that to productWithQuantites
.