Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage on swift can't check for nil

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?

like image 995
Wak Avatar asked Aug 19 '14 23:08

Wak


2 Answers

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! } 
like image 157
drewag Avatar answered Oct 11 '22 12:10

drewag


The simplest way to check if an image has content (> nil) is:

    if image.size.width != 0 { do someting}  
like image 20
Jeremy Andrews Avatar answered Oct 11 '22 11:10

Jeremy Andrews