user3462448 user3462448 - 1 year ago 135
Swift Question

how to add multiple key value pairs to dictionary Swift

okay, i'm trying to have the user add a key and value pair to a dictionary i created and have it show up in a table view. i do that just fine but i cant seem to figure out how to add another pair. when i go to add another it replaces the last one. id really like to have multiple pairs. can someone help please?

heres my code:

//declaring the dictionary
var cart = [String:String]()

//attempting to add to dictionary
cart[pizzaNameLabel.text!] = formatter.stringFromNumber(total)

Avt Avt
Answer Source

This is how dictionary works:

In computer science, an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.


var cart = [String:String]() 
cart["key"] = "one"
cart["key"] = "two"

will print only "key" - "two" part. It seems that you may need an array of tuples instead:

var cart = [(String, String)]() 
cart.append(("key", "one"))
cart.append(("key", "two"))

will print both pairs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download