【问题标题】:Loop through Dictionary in SwiftUI在 SwiftUI 中循环遍历字典
【发布时间】:2022-01-11 05:50:02
【问题描述】:

我有var countriesGroupedByRegion: Dictionary<String, [Array<Country>.Element]> 键(字符串)是区域,数组是该区域内的所有国家/地区。

我需要遍历这本字典,以便创建一个包含与地区一样多的部分的列表,并且在每个部分中,我想显示所有国家...但我不知道如何循环浏览这本字典在 SwiftUI 中使用 ForEach。我当前的代码如下:

NavigationView {
  List {
    ForEach(countriesGroupedByRegion, id: \.self) { region in
                    
    }
  }
}

countriesGroupedByRegion 是提到的字典。我收到以下错误:Cannot convert value of type 'Dictionary<String, [Array<Country>.Element]>'

有人能帮我弄清楚如何遍历这个字典并在 SwiftUI 中创建这些部分吗?

【问题讨论】:

    标签: ios xcode swiftui


    【解决方案1】:

    我建议将字典的(键)映射到区域结构的数组

    struct Region { 
        let name : String
        let countries : [Country]
    } 
    

    这可以在带有id: \.nameForEach 语句中使用。进一步考虑字典是无序的。

    这是一个简单的示例,其中包含一个代表国家/地区的字符串数组

    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
                        
        }
      }
    }
    

    【讨论】:

    • 分解密钥然后强制解包,不如dictionary.sorted { $0.key < $1.key }.map(Region.init)。我使用序列扩展来做到这一点,如dictionary.sorted(by: \.key).map(Region.init)
    • @Jessy 强制解包很好,因为标准的 Swift 字典不能有 nil 值。在字典上调用 map 会创建一个元组数组,就效率而言,它们几乎相同。
    猜你喜欢
    • 2023-04-03
    • 2023-03-12
    • 2022-09-22
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多