Wak
Wak

Reputation: 878

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?

Upvotes: 42

Views: 63001

Answers (6)

Amey Sunu
Amey Sunu

Reputation: 63

You can check for it's width, which would be 0 if no image is uploaded.

if(image.size.width != 0){

      print("image found")

} else {

      print("image is null")

}

Upvotes: 2

iHarshil
iHarshil

Reputation: 779

You can check it's imageAsset like this:

if image.imageAsset != nil
{
    // image is not null
}
else 
{
    //image is null
}

Upvotes: 1

Jeremy Andrews
Jeremy Andrews

Reputation: 837

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

    if image.size.width != 0 { do someting} 

Upvotes: 13

Vijay Rathod
Vijay Rathod

Reputation: 197

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.

Upvotes: 3

skywinder
skywinder

Reputation: 21426

Init, that you are call init?(contentsOfFile path: String) the ? means that it returns optional value.

You should check optional vars for nil before use it.

Shorter, than accepted answer and Swift-style way, than named Optional Chaining to do that:

if let image = UIImage(contentsOfFile: filePath) {
   return image
}

Upvotes: 1

drewag
drewag

Reputation: 94683

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

Upvotes: 58

Related Questions