SwiftUI iterating through dictionary with ForEach

后端 未结 7 1850

Is there a way to iterate through a Dictionary in a ForEach loop? Xcode says

Generic struct \'ForEach\' requires that \'[Str

7条回答
  •  一生所求
    2020-12-03 13:58

    Since it's unordered, the only way is to put it into an array, which is pretty simple. But the order of the array will vary.

    struct Test : View {
    let dict: [String: Int] = ["test1": 1, "test2": 2, "test3": 3]
    var body: some View {
        let keys = dict.map{$0.key}
        let values = dict.map {$0.value}
    
        return List {
            ForEach(keys.indices) {index in
                HStack {
                    Text(keys[index])
                    Text("\(values[index])")
                }
            }
        }
    }
    }
    
    #if DEBUG
    struct Test_Previews : PreviewProvider {
        static var previews: some View {
            Test()
        }
    }
    #endif
    

提交回复
热议问题