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
= UIImage(contentsOfFile: filePath) if image != nil { return image! }
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With