[swift unboxed]

Safely unboxing the Swift language & standard library

Swift Likes ML Option Types

Looking at Swift optionals through an ML lens.

3 June 2014 ∙ Swift Language ∙ written by

Long ago, I learned ML and thought it was a mostly useless academic language. Then Swift comes along and I think, hey! Someone at Apple thought otherwise?

Here’s how option types work in ML: You have a regular type like int, which must have an integer value. Then you have a separate type int option.

If there is no value, you can assign the special value NONE. If there is a value, you need to box it up with the keyword SOME. For example, val age = SOME 34;

Why do you need that SOME? ML is strongly typed, so 34 is an int and not strictly an int option. Thus the SOME box to get around it. Think of NONE and SOME as the same type, so your int option variable can have either of these. The bonus with SOME is that there’s an int buried in there, like treasure.

How does this translate to Swift? Swift is apparently just as strongly typed in this regard. You can declare an optional Int like this:

var optionalInt: Int?

which is just syntactic sugar for this:

var optionalInt: Optional<Int>

Turns out Optional is just an enumeration! And what are its two possible values? Of course: None and Some.

If there is a value assigned, it looks like this:

var optionalInt: Int? = 41
optionalInt   // this is Some(41)
optionalInt?  // this is Some(41)
optionalInt!  // this is the plain Int 41

Note that you have to unbox the optional value with the ! operator.

The question mark version optionalInt? looks nice in a conditional, since Some values evaluate to boolean true:

if optionalInt? {
  println("Your number is \(optionalInt!)")

If there is no value, it looks like this:

var optionalInt: Int?
optionalInt   // this is nil
optionalInt?  // this is nil (like boolean false)
optionalInt!  // runtime error

You cannot unbox nil, so you will get a runtime error.

So don’t be fooled by the dynamic language appearance and auto-type inference of Swift. It’s as strict as a language from the 1970s (but still way cooler).