And then there was .None: when to nil and when to not

I was updating some very old code today, when I stumbled across a return .None for some function that returned T?. It’s been pretty much forever since I have used anything other than return nil and I thought I’d take a quick moment to figure out where .None belongs in my life.

It didn’t take long (thanks, Olivier) to shake out a sketchy rule of thumb. It’s this: if you’re using pattern matching, you can go use .None if you really want to. If you are returning an optional value, just use nil.

if case (.None, .None) = items { return nil }

Even if you can theoretically use:

if case (nil, nil) = items { return nil }

skipping the .None in pattern matching just doesn’t feel as nice, especially when you’re doing any conditional binding:

if case (.Some(let x), .None) = items { ... }

vs

if case (.Some(let x), nil) = items { ... }

but then again, Swift now supports x? vs .Some(let x), so I’m also actually pretty okay with:

if case (let x?, nil) = items { ... }

Conclusive? Not especially but there you have it.

If you are building a custom enumeration and your conversation regularly includes terms like monads and functors, you’re on your own.

3 Comments

  • I need to stop reading these posts. How can I recommend that any company use Swift when the dam thing is being “made up” as we go along.
    The “geniuses” on the Swift team have already decided to “ditch” adherence to long accepted ANSI C standards, and I found this quite on apple.com … “Swift is easy to use and” … what ever happened to “easy to use” part? I’ve beeb coding Swift for over a year, why do they keep “breaking” the language with very major release? How about full-compatability (bindings/ toll-free, whatever, etc.) with Cocoa?

    • Of course it is a little bit annoying that existing code breaks. But on the other hand it is the only way to really improve a language: Either a programming language is backward compatible or a programming language is innovative – especially if the language is still very young. So it is okay to have some inconveniences.

  • I like the last example the most –

    if case (let x?, nil) = items { … }