我有var countriesGroupedByRegion: Dictionary<String, [Array<Country>.Element]>
鍵(字串)是區域,陣列是該區域內的所有國家。
我需要遍歷這本字典,以便我可以創建一個包含與區域一樣多的部分的串列,并且在每個部分中,我想顯示所有國家/地區...但我不知道如何在 SwiftUI 中使用對于每個。我目前的代碼如下:
NavigationView {
List {
ForEach(countriesGroupedByRegion, id: \.self) { region in
}
}
}
countriesGroupedByRegion提到的字典在哪里。我收到以下錯誤:Cannot convert value of type 'Dictionary<String, [Array<Country>.Element]>'
有人可以幫我弄清楚如何遍歷這個字典并在 SwiftUI 中創建部分嗎?
uj5u.com熱心網友回復:
我建議將(的鍵)字典映射到區域結構的陣列
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
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373281.html
