How to determine if UIImage is empty?

How to check if there is no UIImage ?

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

My ViewController code looks like this:

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

self.userData.photo == nil will not work in Swift.

Xcode says: UIImage is not convertible to MirrorDisposition

+5
source share
1 answer

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

The reason is that you declared photo as UIImage. Is this not the same as UIImage? - optional UIImage packaging. Only "Optional" can be zero in Swift. But, as I just said, photo is not optional. Therefore, there is nothing to check. This 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 problem is that you type photo as UIImage? and first set the value to nil (in fact, it is implicit from the very beginning). Now you can check for null to see if the actual image is assigned to it.

    But keep in mind that you have to forget to deploy photo when you want to use it for anything! (Instead, you can enter photo as an implicitly unwrapped optional UIImage! Parameter to avoid this constant sweep, but I'm not so keen on this idea.)

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

+9
source

Source: https://habr.com/ru/post/1211374/


All Articles