NSX
NSX

Reputation: 25

How to add multiple dictionary into array

I've got a dictionary added into array. I would like to add second dictionary into the array. How to do it?

        var dict = [String: AnyObject]()

        dict = ["description": self.odrRefTxt.text as AnyObject,
               "weight": self.pWeight as AnyObject,
               "quantity": self.qtyTxt.text as AnyObject,
               "unitPrice": self.valueTxt.text as AnyObject,
               "currency": self.pCurrency as AnyObject]

        // saving to memory
        UserDefaults.standard.set(dict, forKey: "addItem")

        // getting from memory
        let addItem = UserDefaults.standard.value(forKey: "addItem")
        print(addItem as Any)


        //add new item into list of items
        self.itemArr.append(addItem as Any)
        print(self.itemArr)

Below are the result from print:

 //print addItem
Optional({
        currency = "";
        description = "Toyo Proxes";
        quantity = 4;
        unitPrice = 100;
        weight = 0;
    })

//print self.itemArr
    [Optional({
        currency = "";
        description = "Toyo Proxes";
        quantity = 4;
        unitPrice = 100;
        weight = 0;
    })]

For example, I would like to add the 2nd dictionary into the array to print out the outcome like this:

//print self.itemArr
    [Optional({
        currency = "";
        description = "Toyo Proxes";
        quantity = 4;
        unitPrice = 100;
        weight = 0;
    }, 
{
        currency = "";
        description = "Yokohama Advan";
        quantity = 2;
        unitPrice = 250;
        weight = 0;
    })]

Upvotes: 1

Views: 1342

Answers (1)

Willjay
Willjay

Reputation: 6469

You save something in UserDefaults as Any, so just cast it to the original type and here you go.

Modified with @rmaddy's suggestion.

var itemArr = [[String: Any]]()

var dict = [String: Any]()
dict = ["description": 1,
        "weight": 2,
        "quantity": 3,
        "unitPrice": "abc",
        "currency": "123"]

// saving to memory
UserDefaults.standard.set(dict, forKey: "addItem")

// getting from memory
if let addItem = UserDefaults.standard.dictionary(forKey: "addItem") {
    itemArr.append(addItem)
}

let dict2:[String: Any] = ["description": 4,
        "weight": 5,
        "quantity": 6,
        "unitPrice": "xyz",
        "currency": "456"]

itemArr.append(dict2)
print(itemArr)

// prints out:
// [["description": 1, "quantity": 3, "weight": 2, "currency": 123, "unitPrice": abc], ["description": 4, "weight": 5, "quantity": 6, "currency": "456", "unitPrice": "xyz"]]

Upvotes: 2

Related Questions