I have var countriesGroupedByRegion: Dictionary<String, [Array<Country>.Element]>
键(字符串)是区域,数组是该区域内的所有国家/地区。
我需要循环遍历这本字典,这样我就可以创建一个包含与区域一样多的部分的列表,并且在每个部分中,我想显示所有国家/地区...但我不知道如何使用 SwiftUI 循环遍历这本字典对于每个。我当前的代码如下:
NavigationView {
List {
ForEach(countriesGroupedByRegion, id: \.self) { region in
}
}
}
where countriesGroupedByRegion
是提到的字典。我收到以下错误:Cannot convert value of type 'Dictionary<String, [Array<Country>.Element]>'
有人可以帮我弄清楚如何循环遍历这个字典并在 SwiftUI 中创建各个部分吗?
我建议将字典(的键)映射到区域结构的数组
struct Region {
let name : String
let countries : [Country]
}
这可以用在ForEach
声明与id: \.name
。进一步考虑字典是无序的。
这是一个简单的示例,其中包含代表国家/地区的字符串数组
let dictionary = ["Asia": ["Japan", "India"], "Europe": ["Italy", "Norway"]]
struct Region {
let name : String
let countries : [String]
}
let regions = dictionary
.keys
.sorted()
.map{Region(name: $0, countries: dictionary[$0]!)}
NavigationView {
List {
ForEach(regions, id: \.name) { region in
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)