好吧,我正在尝试让用户将一个键和值对添加到我创建的字典中并让它显示在表格视图中.我这样做很好但我似乎无法弄清楚如何添加另一对.当我去添加另一个时,它取代了最后一个. id真的很喜欢有多对.有人可以帮忙吗?
继承我的代码:
//declaring the dictionary var cart = [String:String]() //attempting to add to dictionary cart[pizzaNameLabel.text!] = formatter.stringFromNumber(total)
这就是
dictionary的工作方式:
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" print(cart)
将只打印“关键” – “两个”部分.看来你可能需要一组元组代替:
var cart = [(String,String)]() cart.append(("key","one")) cart.append(("key","two")) print(cart)
将打印两对.