在 TableView 中迭代字典

发布于 2025-01-13 03:22:27 字数 321 浏览 2 评论 0原文

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

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

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

我想要实现的逻辑:

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

this might be a common situation, but I was not able to figure out a way how to do it.

I have a dictionary with the stock amount for several items: dict = ["item1" : 2, "item2" : 5, "item3" : 10 ]

How can I now assign the keys and values to different labels in a tableView, using indexPath?

The logic I want to achieve:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与酒说心事 2025-01-20 03:22:27

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

我的建议是将字典映射到自定义结构的数组,并按对数组进行排序

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

A dictionary as data source can be annoying because a dictionary is unordered.

My suggestion is to map the dictionary to an array of a custom struct and sort the array by the keys

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}

Then in the table view you can write

cell.itemLabel.text = array[indexPath.row].name
冷默言语 2025-01-20 03:22:27

您可以使用映射函数来获取单独的键和值数组

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]

You can use map function to get separate array of key and values

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

Try this:

cell.itemLabel.text = dict.map({$0.key})[indexPath.row]
cell.amountLabel.text = dict.map({$0.value})[indexPath.row]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文