微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将多个键值对添加到字典Swift中

好吧,我正在尝试让用户一个键和值对添加到我创建的字典中并让它显示在表格视图中.我这样做很好但我似乎无法弄清楚如何添加另一对.当我去添加一个时,它取代了最后一个. 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)

将打印两对.

原文地址:https://www.jb51.cc/swift/318875.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐