Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine whether a UIImage is empty?

Tags:

ios

swift

uiimage

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

like image 674
Morten Gustafsson Avatar asked Jan 18 '15 20:01

Morten Gustafsson


People also ask

How do I check if an image is empty in Swift?

= UIImage(contentsOfFile: filePath) if image != nil { return image! }

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .

How do I find my UIImage path?

Once a UIImage is created, the image data is loaded into memory and no longer connected to the file on disk. As such, the file can be deleted or modified without consequence to the UIImage and there is no way of getting the source path from a UIImage.


1 Answers

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!

like image 199
matt Avatar answered Sep 20 '22 18:09

matt