加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:20:36 所属栏目:百科 来源:网络整理
导读:好吧,我正在尝试让用户将一个键和值对添加到我创建的字典中并让它显示在表格视图中.我这样做很好但我似乎无法弄清楚如何添加另一对.当我去添加另一个时,它取代了最后一个. id真的很喜欢有多对.有人可以帮忙吗? 继承我的代码: //declaring the dictionaryva
好吧,我正在尝试让用户将一个键和值对添加到我创建的字典中并让它显示在表格视图中.我这样做很好但我似乎无法弄清楚如何添加另一对.当我去添加另一个时,它取代了最后一个. 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)

将打印两对.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读