SwiftUI iterating through dictionary with ForEach

后端 未结 7 1874

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:53

    Here is how I implemented this:

    struct CartView: View {
        var cart:[String: Int]
    
        var body: some View {
            List {
                ForEach(cart.keys.sorted()) { key in
                    Text(key)
                    Text("\(cart[key]!)")
                }
            }
        }
    }
    

    The first Text View will output the key which is a String. The second Text View will output the value of the Dict at that key which is an Int. The ! that follows this is to unwrap the Optional which contains this Int. In production you would perform checks on this Optional for a more safe way of unwrapping it, but this is a proof of concept.

提交回复
热议问题