0
votes
var image = self.imageData[index] as NSString     
        if let derp = image as NSString? {
            println(" \(image)")
        } else {
            println("is nil")
        }

        dataViewController.dataImage.image = UIImage(named: image) as UIImage

That last line:

dataViewController.dataImage.image = UIImage(named: image) as UIImage

gives me "Can't unwrap Optional.None", despite the image object successfully passing the optional binding test as shown here https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_428 . The image string does print at the bottom of Xcode.

2

2 Answers

1
votes

It is possible you are getting that error because an image with that name does not exist. However, you also have some issues with your optional binding.

  1. Optional binding is different from casting. You don't provide a new type. Also, even if casting was the way to do it, you are casting to an optional, which doesn't prove that image is not nil.

  2. You have already asserted to the compiler that image is not nil with your as NSString on the first line. If this conversion is not successful at runtime, your whole app will crash.

  3. After binding an optional, you should use the local variable, not use the optional later

This means your code should look like this:

var possibleImageName = self.imageData[index] as? NSString     
if let imageName = possibleImageName {
    var possibleImage : UIImage? = UIImage(named: imageName)
    if let image = possibleImage {
        dataViewController.dataImage.image = image
    }
} else {
    println("is nil")
}

After you understand the optional binding process, and the difference from casting, you can shorten the code to this:

if let imageName = self.imageData[index] as? NSString {
    if let image = UIImage(named: imageName) as UIImage? {
        dataViewController.dataImage.image = image
    }
} else {
    println("is nil")
}

Note: The check for nil from initializers is strange. You have to cast it to be an optional type so that you can actually test it because initializers from Objective-C actually return Implicitly Unwrapped Optionals.

1
votes

UIImage(named:) may return nil in case the image with given name cannot be found. You need to check it did not nil.

var img : UIImage? = UIImage(named: image)
if img != nil {
    dataViewController.dataImage.image = img!
}

or

if let img = UIImage(named: image) as UIImage! {
    dataViewController.dataImage.image = img
}