how to add multiple key value pairs to dictionary Swift

14,203

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.

So

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

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"))
print(cart)

will print both pairs.

Share:
14,203
user3462448
Author by

user3462448

Updated on July 12, 2022

Comments

  • user3462448
    user3462448 almost 2 years

    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)