SwiftUI使用ForEach遍历字典 [英] SwiftUI iterating through dictionary with ForEach
问题描述
是否有一种方法可以在ForEach
循环中循环访问Dictionary
? Xcode说
Is there a way to iterate through a Dictionary
in a ForEach
loop? Xcode says
通用结构'ForEach'要求'[String:Int]'符合'RandomAccessCollection'
Generic struct 'ForEach' requires that '[String : Int]' conform to 'RandomAccessCollection'
那么有没有办法使Swift字典符合RandomAccessCollection
,或者因为字典是无序的,那是不可能的吗?
so is there a way to make Swift Dictionaries conform to RandomAccessCollection
, or is that not possible because Dictionaries are unordered?
我尝试过的一件事是迭代字典的键:
One thing I've tried is iterating the dictionary's keys:
let dict: [String: Int] = ["test1": 1, "test2": 2, "test3": 3]
...
ForEach(dict.keys) {...}
但是keys
不是String
的数组,它的类型是Dictionary<String, Int>.Keys
(不确定何时更改).我知道我可以编写一个辅助函数,该函数接受字典并返回键的数组,然后可以迭代该数组,但是没有内置的方法或更优雅的方法吗?我可以扩展Dictionary
并使它符合RandomAccessCollection
之类的东西吗?
But keys
is not an array of String
s, it's type is Dictionary<String, Int>.Keys
(not sure when that was changed). I know I could write a helper function that takes in a dictionary and returns an array of the keys, and then I could iterate that array, but is there not a built-in way to do it, or a way that's more elegant? Could I extend Dictionary
and make it conform to RandomAccessCollection
or something?
推荐答案
简单答案:否.
正如您正确指出的那样,字典是无序的. ForEach监视他的收藏中是否有更改.此更改包括插入,删除,移动和更新.如果发生任何这些更改,将触发更新.参考: https://developer.apple.com/videos/play/wwdc2019/204/在46:10:
As you correctly pointed out, a dictionary is unordered. The ForEach watches his collection for changes. This changes includes inserts, deletions, moves and update. If any of those changes occurs, an update will be triggered. Reference: https://developer.apple.com/videos/play/wwdc2019/204/ at 46:10:
ForEach自动监视其收藏夹中的更改
A ForEach automatically watches for changes in his collection
我建议您观看讲话:)
您不能使用ForEach,因为:
You can not use a ForEach because:
- 它监视收藏并监视动作.不可修改的字典是不可能的.
- 重用视图时(例如
UITableView
在可回收单元时重用单元,List
由UITableViewCells
支持,我认为ForEach
在做相同的事情),它需要计算什么要显示的单元格.它通过查询数据源的索引路径来实现.从逻辑上讲,如果数据源是无序的,则索引路径是无用的.
- It watches a collection and monitors movements. Impossible with an unorered dictionary.
- When reusing views (like a
UITableView
reuses cells when cells can be recycled, aList
is backed byUITableViewCells
, and I think aForEach
is doing the same thing), it needs to compute what cell to show. It does that by querying an index path from the data source. Logically speaking, an index path is useless if the data source is unordered.
这篇关于SwiftUI使用ForEach遍历字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!