简体   繁体   中英

How to iterate through a dictionary in swift

When my structure is called/referenced, the country name is passed into it (ie "United Kingdom"). I then want to search for all the items that are in that country in the 'items' dict, and display just the description property of each one in a navigation list.

I don't really understand what the problem is, let alone the solution.

Here are the errors:

这是错误

And here are the expanded errors when i click on the first one:

ForEach 上的错误

Here's the entirety of the code:

import SwiftUI

struct CountryView: View {
    var country: String // Country name is passed in when struct called
    
    let items = [
        "United Kingdom": [
            [
                "description":"Diamond-Encrusted Ring",
                "image":"placeholder",
                "category":"jewellery",
                "location":"Tate Modern Museum"
            ],
            [
                "description":"Red Baseball Cap",
                "image":"placeholder",
                "category":"clothing",
                "location":"Old Trafford Stadium"
            ]
        ],
        "United States": [
            [
                "description":"Apple Watch",
                "image":"placeholder",
                "category":"device",
                "location":"Empire State Building"
            ]
        ]
    ]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(items, id: \.self) { item in
                    NavigationLink(destination: ItemView(item: item)) {
                        Text(item.description)
                    }
                }
            }.navigationTitle(country)
        }
    }
}

struct CountryView_Previews: PreviewProvider {
    static var previews: some View {
        CountryView(country: "United Kingdom")
    }
}

I know for a fact that this question is confusing, so feel free to edit it to make it a little clearer. I just can't think of a better way to explain it, since I have no idea what's going on. Thanks in advance.

As per advice from a commenter, I switched to using a model rather than a dict. It worked, Although I'm not sure it was supposed to be a solution, and more just a tip. it solved the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM