【问题标题】:Making a list with dictionary [duplicate]用字典制作列表[重复]
【发布时间】:2021-11-28 10:46:48
【问题描述】:

我正在尝试用字典制作一个列表。我的字典位于模型中。我的字典是 [String : String]。我试图对其进行排序,希望它按字母顺序排序。我不明白为什么它不起作用

var fw:  Deck

 var body: some View {
                
        let sortedDict  = fw.dictItems.sorted(by:  < )
        let keys = sortedDict.map {$0.key}
        let values = sortedDict.map {$0.value}
  return List{

            ForEach(keys.indices) { index in
                    HStack {
                        Text(keys[index])
                        Text("\(values[index])")
                    }
                }
}
 }
        
            }

【问题讨论】:

    标签: dictionary foreach swiftui


    【解决方案1】:

    这里有一个适合你的方法:

    struct ContentView: View {
        
        @State var entries: [String: String] = ["key1":"val1", "key2":"val2", "key3":"val3", "key4":"val4"]
        
        var body: some View {
            List {
                ForEach(entries.keys.sorted(by: <), id: \.self) { key in
                    HStack {
                        Text(key)
                        
                        Text(entries[key]!)
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-20
      • 2022-11-30
      • 2015-07-29
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 2012-05-14
      • 1970-01-01
      相关资源
      最近更新 更多