skip to Main Content

I am trying to utilize the UIImage array in SWiftUI class for forEach loop but Xcode always gives me the error ‘Failed to produce diagnostic for expression;’. I also tried using the Data array but same error. Below is my code. It will be great if someone can point what I am doing wrong?

struct Sample: View {

    let imageArray: [UIImage]

    var body: some View {
        ForEach(imageArray) { image in
            Image(uiImage: image)
        }
    }
}

3

Answers


  1. Chosen as BEST ANSWER

    I was able to fix the problem by adding id in ForEach loop. Below is how my code looks now.

    struct ImageData: Identifiable {
        let id = UUID()
        let image: UIImage
    }
    
    struct Sample: View {
    
        let imageDataArray: [ImageData]
    
        var body: some View {
            ForEach(imageDataArray) { imageData in
                Image(uiImage: imageData.image)
            }
        }
    }
    

    What I learned from here is, for objects such as UIImage, if you need to enumerate, you must add id property on the ForEach loop. To solve the problem, I created a model class containing id and image property and enumerated it.


  2. The ForEach operator requires elements of the array to conform to identifiable. For something like UIImage, you can just pass self.

    var body: some View {
        ForEach(imageArray, id: .self) { image in
            Image(uiImage: image)
        }
    }
    

    Personally, I would also wrap it in a Stack, just to be explicit

    var body: some View {
        VStack {
            ForEach(imageArray, id: .self) { image in
                Image(uiImage: image)
            }
        }
    }
    
    Login or Signup to reply.
  3. this works for me:

    import SwiftUI
    
    @main
    struct TestApp: App {
        var body: some Scene {
            WindowGroup {
                ContentView()
            }
        }
    }
    struct Sample: View {
        let imageArray: [UIImage]
        
        var body: some View {
            ForEach(imageArray, id: .self) { image in
                Image(uiImage: image)
            }
        }
    }
    
    struct ContentView: View {
        @State var imageArray: [UIImage] = []
        
        var body: some View {
            Sample(imageArray: imageArray)
                .onAppear {
                    if let img = UIImage(systemName: "globe") {
                        imageArray.append(img)
                    }
                }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search