swift上的UIImage无法检查是否为零 [英] UIImage on swift can't check for nil
问题描述
我在Swift上有以下代码
I have the following code on Swift
var image = UIImage(contentsOfFile: filePath)
if image != nil {
return image
}
它过去效果很好,但是现在在Xcode Beta 6上,这会返回一个警告
It used to work great, but now on Xcode Beta 6, this returns a warning
'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
}
但错误更改为:
Bound value in a conditional binding must be of Optional type
这是Xcode6 beta 6上的错误还是我做错了什么?
Is this a bug on Xcode6 beta 6 or am I doing something wrong?
推荐答案
更新
Swift现在添加了可用的初始化器和UIImage的概念现在是其中之一。初始化程序返回一个Optional,所以如果无法创建图像,它将返回nil。
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.
默认情况下,变量不能为零
。这就是为什么在尝试将 image
与 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:
let image: UIImage? = UIImage(contentsOfFile: filePath)
if image != nil {
return image!
}
这篇关于swift上的UIImage无法检查是否为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!