繁体   English   中英

在 TableView 中遍历字典

[英]iterating through dictionary in TableView

这可能是一种常见的情况,但我无法想出一种方法来做到这一点。

我有一本字典,其中包含多个项目的库存量: dict = ["item1": 2, "item2": 5, "item3": 10 ]

我现在如何使用indexPath将键和值分配给 tableView 中的不同标签?

我要实现的逻辑:

cell.itemLabel.text = dict.[firstItemName]
cell.amountLabel.text = dict.[firstItemAmount]

作为数据源的字典可能很烦人,因为字典是无序的。

我的建议是将字典map为自定义结构的数组,并按键对数组进行排序

struct Model {
    let name : String
    let value: Int
}

let dict = ["item1" : 2, "item2" : 5, "item3" : 10 ]

let array = dict.map(Model.init).sorted{$0.name < $1.name}

然后在表格视图中你可以写

cell.itemLabel.text = array[indexPath.row].name

您可以使用 map function 来获取单独的键和值数组

print(dict.map({$0.key}))
print(dict.map({$0. value}))

尝试这个:

cell.itemLabel.text = dict.map({$0.key})[indexPath.row]
cell.amountLabel.text = dict.map({$0.value})[indexPath.row]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM