[英]How do I determine whether a UIImage is empty?
How do I check to see if a UIImage
is empty? 如何检查
UIImage
是否为空?
class UserData {
...
var photo: UIImage = UIImage()
}
My ViewController
code looks like: 我的
ViewController
代码如下所示:
var userData = UserData()
...
func preparePhoto(){
if (self.userData.photo == nil) {
...
}else{
...
}
}
self.userData.photo == nil
won't work in Swift. self.userData.photo == nil
在Swift中不起作用。
Xcode says: UIImage is not convertible to MirrorDisposition
Xcode说:
UIImage is not convertible to MirrorDisposition
self.userData.photo
will never be nil, so the question is pointless. self.userData.photo
永远不会是零,所以这个问题毫无意义。
The reason is that you have declared photo
as a UIImage. 原因是您已将
photo
声明为UIImage。 That is not the same as a UIImage?
那和
UIImage?
不一样UIImage?
- an Optional wrapping a UIImage. - 包装UIImage的可选项。 Only an Optional can be nil in Swift.
在Swift中只有一个可选的nil。 But, as I just said,
photo
is not an Optional. 但是,正如我刚才所说,
photo
不是可选的。 Therefore there is nothing to check. 因此无需检查。 That is why Swift stops you when you try to perform such a check.
这就是为什么当你试图执行这样的检查时Swift会阻止你。
So, what to do? 那么该怎么办? I have two possible suggestions:
我有两个可能的建议:
My actual recommendation for solving this is that you do type photo
as a UIImage?
我对解决这个实际的建议是, 你键入
photo
作为UIImage?
and set it initially to nil (actually, it is implicitly nil from the start). 并将其初始设置为nil(实际上,它从一开始就隐含为nil)。 Now you can check for nil to see whether an actual image has been assigned to it.
现在您可以检查nil以查看是否已为其分配实际图像。
But keep in mind that you then will have to remember to unwrap photo
when you want to use it for anything! 但请记住,当您想要将
photo
用于任何事情时,您必须记得打开photo
! (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.) (你可以改为将
photo
键入一个隐式解开的可选UIImage!
以避免不断展开,但我不是那么热衷于这个想法。)
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!
如果它是零大小,它可能是你问题的原始意义上的空图像!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.