简体   繁体   中英

How do I determine whether a UIImage is empty?

How do I check to see if a UIImage is empty?

class UserData {
    ...
    var photo: UIImage = UIImage()
}

My ViewController code looks like:

var userData = UserData()
    ...

func preparePhoto(){
        if (self.userData.photo == nil) {
            ...
        }else{
            ...
        }
    }

self.userData.photo == nil won't work in Swift.

Xcode says: UIImage is not convertible to MirrorDisposition

self.userData.photo will never be nil, so the question is pointless.

The reason is that you have declared photo as a UIImage. That is not the same as a UIImage? - an Optional wrapping a UIImage. Only an Optional can be nil in Swift. But, as I just said, photo is not an Optional. Therefore there is nothing to check. That is why Swift stops you when you try to perform such a check.

So, what to do? I have two possible suggestions:

  • My actual recommendation for solving this is that you do type photo as a UIImage? and set it initially to nil (actually, it is implicitly nil from the start). Now you can check for nil to see whether an actual image has been assigned to it.

    But keep in mind that you then will have to remember to unwrap photo when you want to use it for anything! (You could instead type photo as an implicitly unwrapped optional, UIImage! , to avoid that constant unwrapping, but I am not as keen on that idea.)

  • An alternative possibility would be to examine the size of the image. If it is zero size, it is probably an empty image in the original sense of your question!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM