0

I'm using Apple's VisionKit and storing the images in both an Image and Data array, like so:

@State private var image: [Image] = []
@State var imageData : Data = .init(count: 0)

And appending the data like this:

for imageIndex in imagePerPage! {
  var uiImage = UIImage(cgImage: imageIndex)
  let converted = Image(uiImage: uiImage)
  image.append(converted)
  imageData.append(uiImage.jpegData(compressionQuality: 0.00005)!)
}

I'm passing the data to another view which is fine, as I can use print(image.count) and I get the expected count. However, I'm having issues with iterating over my array and display the images. I use a ForEach statement and I get an error nagging me that the data type Image must conform to Hashable (I'm not using a model/struct)

@State var image: [Image]

 ForEach(image.count, id: \.self) { image in
  Image(image)
  .resizable()
  .frame(width: getScreen().width, height: getScreen().height * 0.85)
   .aspectRatio(contentMode: .fit)
}

I've even tried a for loop i.e. for x in images {///}.

Is there anyway in which I can resolve this issue?

Would be much appreciated!

1 Answer 1

4

You can use ForEach with a range: 0...10.

Secondly, your image array already holds Images, so you shouldn't need to call Image again.

ForEach(0..<image.count) { imageIdx in
           image[imageIdx]
           .resizable()
           .frame(width: getScreen().width, height: getScreen().height * 0.85)
           .aspectRatio(contentMode: .fit)
        }

Now, that being said, I'm a little skeptical of the idea of keeping the Image views in the array. I think you'd be better off making your array full of UIImage objects and then calling them inside the view with Image(uiImage:) inside your view.

Might look more like this:

@State var images: [UIImage]
    
var body: some View {
        ForEach(0..<images.count) { imageIdx in
           Image(uiImage: images[imageIdx])
           .resizable()
           .frame(width: getScreen().width, height: getScreen().height * 0.85)
           .aspectRatio(contentMode: .fit)
        }
}

Finally, using ForEach with indexes instead of IDs could lead to funny issues later if your array gets updated with images as SwiftUI may not know to refresh the view. At that point, it would be better to use a struct wrapper for the images and give them real IDs.

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.