How to convert 'Binding<UIImage>' to expected argument type 'UIImage'

Problem

In SwiftUI 3, I got an error "Cannot convert value of type 'Binding' to expected argument type 'UIImage'".

The Elements to display is Binding type, so I want to know:

  • How to Remove Binding attribute from variable? Biding -> UIimage?
  • Please tell us how to display Binding element in SwiftUI

code

/**
@State private var results: [ImageData] = []
struct ImageData: Identifiable {
  var id: UUID
  var image: UIImage
}
**/
List($results) { $result in
     Image(uiImage: result.image)
                 .resizable()
                 .scaledToFit()
 } // works fine
 ForEach($results) { $result in
      Image(uiImage: $result.image)
 } // has error

Environment Info

  • XCode13.4.1

Accepted Reply

Doing this, like you did in the List example, works fine:

ForEach($results) { $result in
    Image(uiImage: result.image)
}


Because you are passing a Binding of a collection to the data parameter of the ForEach, the content closure expects to be passed a Binding of one of the collection’s elements. This is why you can access this value with the $ prefix and then read the underlying value, in your case ImageData, without it.

  • Works Fine, and thank you for telling me the meaning of $ prefix.

Add a Comment

Replies

Did you try:

ForEach($results) { result in
      Image(uiImage: result.image)
}

The Binding is on results.

Doing this, like you did in the List example, works fine:

ForEach($results) { $result in
    Image(uiImage: result.image)
}


Because you are passing a Binding of a collection to the data parameter of the ForEach, the content closure expects to be passed a Binding of one of the collection’s elements. This is why you can access this value with the $ prefix and then read the underlying value, in your case ImageData, without it.

  • Works Fine, and thank you for telling me the meaning of $ prefix.

Add a Comment