Search code examples
swiftuiswiftui-list

SwiftUI: Using a ForEach to dynamically load Images


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)

            }

Solution

  • 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)
                        }
                    }
            }
        }
    }