swift上的UIImage无法检查是否为零

Wak*_*Wak 37 xcode uiimage ios swift

我在Swift上有以下代码

var image = UIImage(contentsOfFile: filePath)
        if image != nil {
           return image
       }
Run Code Online (Sandbox Code Playgroud)

它过去工作得很好,但现在在Xcode Beta 6上,它会返回一个警告

 'UIImage' is not a subtype of 'NSString'
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么做,我尝试了不同的东西

 if let image = UIImage(contentsOfFile: filePath) {
            return image
   }
Run Code Online (Sandbox Code Playgroud)

但错误变为:

Bound value in a conditional binding must be of Optional type
Run Code Online (Sandbox Code Playgroud)

这是Xcode6 beta 6上的错误还是我做错了什么?

dre*_*wag 54

更新

Swift现在添加了可用的初始化器的概念,UIImage现在就是其中之一.初始化程序返回一个Optional,因此如果无法创建图像,它将返回nil.


默认情况下不能使用变量nil.这就是为什么您要比较的时候得到一个错误imagenil.您需要将变量明确定义为可选:

let image: UIImage? = UIImage(contentsOfFile: filePath)
if image != nil {
   return image!
}
Run Code Online (Sandbox Code Playgroud)


Jer*_*ews 10

检查图像是否有内容 (> nil) 的最简单方法是:

    if image.size.width != 0 { do someting} 
Run Code Online (Sandbox Code Playgroud)