I have a parent view that has:
@State private var myImage:UIImage? = nil
I have a child view that wants to use it:
@Binding var myImage: UIImage?
Issue is it breaks my Coordinator call within that child view:
func makeCoordinator() -> Coordinator {
Coordinator(parent: self, myImage: $myImage)
// error "Cannot convert value of type 'Binding<UIImage?>' to expected argument type 'Binding<UIImage>'"
}
When all the optionals are removed, there is no error with the makeCoordinator function in my child view. What is the proper way to handle this?
The Error is thrown since your Coordinator apparently expects the myImage not to be Binding<Optional<UIImage>> but rather the Binding<UIImage>. The difference is significant, and the solution will depend on the desired design of your code.
Remove the ? to no longer deal with Optional, this will probably not suite your need but it's an option.
// in your parent
@State private var myImage: UIImage
// and child implementation
@Binding var myImage: UIImage
Add the ? to make the Binding<UIImage> a Binding<Optional<UIImage>>. Again, may not be best solution for your needs.
// in your Coordinator implementation
@Binding var myImage: UIImage?
I would recommend the following:
func makeCoordinator() -> Coordinator {
Coordinator(parent: self, myImage: Binding(
get { myImage ?? UIImage() }, // or some other default value
set { myImage = $0 }
))
}
The solution really depends on what you are trying to achieve really. You need to decide if you actually want the Optional to be in the Coordinator or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With