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 Dictionaries 符合 RandomAccessCollection
,或者这是不可能的,因为 Dictionaries 是无序的?
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
(不确定何时被改变了).我知道我可以编写一个辅助函数,它接受字典并返回一个键数组,然后我可以迭代该数组,但是没有内置的方法来做到这一点,或者更优雅的方法?我可以扩展 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 its collection for changes. These 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屋!