Home > Net >  How to iterate through array of Images in SwiftUI eloquently?
How to iterate through array of Images in SwiftUI eloquently?

Time:02-02

I'd like to iterate through array of Images https://developer.apple.com/documentation/swiftui/image

in manner like List(images) or ForEach(images) but not through indexes of the array

List(images, id : \.hashValue){ $0 }

for using List or ForEach, Image must be hashable or identifiable

extension Image: Hashable{
     public func hash(into hasher: inout Hasher) {
        hasher.combine( / some value / )
    }
}

what'd better to use as a parameter for "combine" ? or any suggestions how to implement looping eloquently ?

CodePudding user response:

How about wrapping each image in an Identifiable struct, and then using the id as the hash value…

struct ImageModel: Identifiable, Hashable {
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    let id = UUID()
    let image: Image
}

struct ContentView: View {
    
    let images = [ImageModel(image:Image(systemName: "questionmark")),
                  ImageModel(image:Image(systemName: "square")),
                  ImageModel(image:Image(systemName: "circle"))]
        
    var body: some View {
        List {
            ForEach(images) { model in
                model.image
            }
        }
    }
}

CodePudding user response:

SwiftUI is a declarative language and asking how to iterate something is imperative so it's not possible.

  • Related