ios swift 上的 UIImage 无法检查 nil
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25394536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UIImage on swift can't check for nil
提问by Wak
I have the following code on Swift
我在 Swift 上有以下代码
var image = UIImage(contentsOfFile: filePath)
if image != nil {
return image
}
It used to work great, but now on Xcode Beta 6, this returns a warning
它曾经很好用,但现在在 Xcode Beta 6 上,这会返回一个警告
'UIImage' is not a subtype of 'NSString'
I don't know what to do, I tried different things like
我不知道该怎么办,我尝试了不同的事情,例如
if let image = UIImage(contentsOfFile: filePath) {
return image
}
But the error changes to:
但错误变为:
Bound value in a conditional binding must be of Optional type
Is this a bug on Xcode6 beta 6 or am I doing something wrong?
这是 Xcode6 beta 6 上的错误还是我做错了什么?
回答by drewag
Update
更新
Swift now added the concept of failable initializers and UIImage is now one of them. The initializer returns an Optional so if the image cannot be created it will return nil.
Swift 现在添加了可失败初始值设定项的概念,而 UIImage 现在是其中之一。初始值设定项返回一个 Optional,因此如果无法创建图像,它将返回 nil。
Variables by default cannot be nil
. That is why you are getting an error when trying to compare image
to nil
. You need to explicitly define your variable as optional:
默认情况下变量不能是nil
. 这就是为什么您在尝试image
与nil
. 您需要将变量明确定义为optional:
let image: UIImage? = UIImage(contentsOfFile: filePath)
if image != nil {
return image!
}
回答by Jeremy Andrews
The simplest way to check if an image has content (> nil) is:
检查图像是否有内容 (> nil) 的最简单方法是:
if image.size.width != 0 { do someting}
回答by Vijay Rathod
func imageIsNullOrNot(imageName : UIImage)-> Bool
{
let size = CGSize(width: 0, height: 0)
if (imageName.size.width == size.width)
{
return false
}
else
{
return true
}
}
the Above method call Like as :
上述方法调用如下:
if (imageIsNullOrNot(selectedImage))
{
//image is not null
}
else
{
//image is null
}
here, i check image size.
在这里,我检查图像大小。
回答by skywinder
Init, that you are call init?(contentsOfFile path: String)
the ?
means that it returns optionalvalue.
Init,你调用init?(contentsOfFile path: String)
的?
意思是它返回可选值。
You should check optional vars for nil
before use it.
nil
在使用它之前,您应该检查可选变量。
Shorter, than accepted answer and Swift-styleway, than named Optional Chainingto do that:
比接受的答案和Swift 风格的方式更短,比命名Optional Chaining更短:
if let image = UIImage(contentsOfFile: filePath) {
return image
}
回答by iHarshil
You can check it's imageAsset like this:
您可以像这样检查它的 imageAsset:
if image.imageAsset != nil
{
// image is not null
}
else
{
//image is null
}