SwiftUI iterating through dictionary with ForEach

后端 未结 7 1844

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 14:09

    I was trying to figure this out as well with a Dictionary of enum/Int pairs. I am effectively converting it to array as Andre suggests, but instead of using map I just cast the keys.

    enum Fruits : Int, CaseIterable {
        case Apple = 0
        case Banana = 1
        case Strawberry = 2
        case Blueberry = 3
    }
    
    struct ForEachTest: View {
        var FruitBasket : [Fruits: Int] = [Fruits.Apple: 5, Fruits.Banana : 8, Fruits.Blueberry : 20]
        var body: some View {
            VStack {
                ForEach([Fruits](FruitBasket.keys), id:\Fruits.hashValue) { f in
                    Text(String(describing: f) + ": \(self.FruitBasket[f]!)")
                }
            }
        }
    }
    
    struct ForEachTest_Previews: PreviewProvider {
        static var previews: some View {
            ForEachTest()
        }
    }
    

提交回复
热议问题