Implicit unwrappage and nil checks

With apologies to the Rolling Stones, failable initializers enforce the you don’t always get what you want rule. For example, NSURL(string:”blah:/123\\zd”) or UIImage(named:”notarealresourcename”) both return nil instead of wrapped instances. There are several early-return ways to deal with this reality.

I’m specifically interested in hearing thoughts about the following pattern, which goes like this:

let x : SomeType! = constructor(...args...) // impl. unwrap.
if (x == nil) return
...use x...

The implicit unwrapping applies when the variable is first accessed and not during the nil check. If you omit the nil check (something that the compiler does not check for) you’re going to run into trouble when using x. Which sort of defeats the whole safety thing.

Here’s an example. This function compiles, runs, works.  If you comment out the nil check line, it still compiles, still runs, still works so long as the image returned is valid. but call it it with a non-existent image and it’s crashsville.

func image(name:String) -> Bool {
    var image : UIImage! = UIImage(named:name)
    if (image == nil) {return false}
    return true

So how do you feel about this pattern? Is it fundamentally different from this?

let failable : Type? = constructor(...args...)
if (failable == nil) return
let unfailable : Type = failable! // unwrap
...use unfailable...

It uses fewer variables and fewer lines, but is it improved substantially? I’d like to know what you think.

Comments are closed.