Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a binding with an optional UIImage?

Tags:

ios

swift

swiftui

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?

like image 278
Rolando Avatar asked Nov 20 '25 23:11

Rolando


1 Answers

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.

1. Get rid of Optionals

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

2. Introduce Optionals to the Coordinator

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?

3. Provide new Binding with some default value

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.

like image 123
Witek Bobrowski Avatar answered Nov 23 '25 03:11

Witek Bobrowski