Convert array data model to dictionary (swift)

Aldo Lazuardi picture Aldo Lazuardi · Feb 5, 2016 · Viewed 8.5k times · Source

Data Model

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

  }
}

Dictionary

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 {
........
}

I've array from data model that i'd like to show it as dictionary, and i got confused to change it. How to convert cart's array (DataCart) to dictionary?

Answer

NSGangster picture NSGangster · Feb 5, 2016
    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)
       }
 }