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?
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)
}
}
It's good practice to make conversion at class level.
So in future if you have more keys, you just need to change at class level only instead of changing in all the places where you have used the same.
Add one calculated property dictionayDataCart
in class as below.
Also add one method "convertDataCartArrayToProductsDictionary:
" which will convert your array of objects to dictionary.
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 dictionaryDataCart : [String : AnyObject] {
var objDict : [String : AnyObject]!
if let icon = self.icon {
objDict["icon"] = icon;
}
objDict["cartId"] = self.cartId;
objDict["price"] = price;
objDict["productName"] = productName;
objDict["quantity"] = quantity;
return objDict;
}
class func convertDataCartArrayToProductsDictionary(arrayDataCart : [DataCart]) -> Dictionary<String,AnyObject> {
var arrayDataCartDictionaries : Array<Dictionary<String,AnyObject>> = Array()
for objDataCart in arrayDataCart {
arrayDataCartDictionaries.append(objDataCart.dictionary);
}
return ["products" : arrayDataCartDictionaries];
}
}
Use method as below.
let arrayDataCarts : [DataCart] = //value of your array
//pass it to class function and you will get your result
let productsDict = let productsDict = DataCart.convertDataCartArrayToProductsDictionary(arrayDataCarts);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With