数据模型

class DataCart {
   var icon: UIImage?
   var cartId: String
   var price: Int
   var productName: String
   var quantity: Int


init(icon: UIImage?, cartId: String, price: Int, productName: String, quantity: Int){
    self.icon = icon
    self.cartId = cartId
    self.price = price
    self.productName = productName
    self.quantity = quantity

  }
}

字典
var cart = [DataCart]()

"products": [[
    "productName": "Photobook", //"dataCart.productName"
    "quantity": 2,   //"dataCart.quantity"
    "price": "5000.00",  //"dataCart.price"
    "pages": 40
    ],[
    "productName": "Photobook2",
    "quantity": 5,
    "price": "7000.00",
    "pages": 30
    ]]

for dataCart in cart {
........
}

我想从数据模型中将其显示为字典,但是我很困惑地对其进行更改。如何将购物车的数组(DataCart)转换为字典?

最佳答案

    var allDictionaries : [[String : AnyObject]]//array of all dictionaries.

    func convertArrayToDictionaries([DataCart]) {
       for data in DataCart {
          let  dictionary = [
             "icon" : data.icon,
             "cartId" : data.cartId,
             "price" : data.price,
             "productName" : data.productName,
             "quantity" : data.quantity
          ]
          allDictionaries.append(dictionary)
       }
 }

09-11 18:35