Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 343
user3462448 Avatar asked Sep 15 '16 21:09

user3462448


1 Answers

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.

like image 116
Avt Avatar answered Nov 21 '22 04:11

Avt