UIImage on swift can't check for nil

Wak picture Wak · Aug 20, 2014 · Viewed 49.3k times · Source

I have the following code on 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

 '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?

Answer

drewag picture drewag · Aug 20, 2014

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.


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!
}