0

I have a handful of images with names such as area, volume, etc.

I want to use data to drive the images displayed. This is an example of what places can be:

   let places = {
      names: ["area", "volume"]
   }

I tried something like this below but getting Referencing initializer 'init(_:content:)' on 'ForEach' requires that 'String' conform to 'Identifiable'

    ForEach(places.name) { place in
        NavigationLink (destination: Any()) {
            HStack {
                Image(place)

            }

1 Answer 1

2

For types like String that don't directly conform to Identifiable, you can tell the ForEach what property to use as an id. Often with String, you'll want to use .self (note this can yield funny results if the Strings are not unique).

struct Places {
    var names : [String]
}

struct ContentView : View {
    let places : Places = Places(names: ["area", "volume"])
    
    var body: some View {
        ForEach(places.names, id:\.self) { place in
                NavigationLink (destination: Text("Detail")) {
                    HStack {
                        Image(place)
                    }
                }
        }
    }
}


Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.