Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

ios - How to use a binding with an optional UIImage?

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...