Please explain how Swift’s Optional
type builds on the work of ML family languages.
Swift's Optional
type represents values that may not be present. Optionals at first appear similar to null
/ nil
in languages like C, Java, and Python, but that similarity is only superficial. Swift optionals are instead based on the option
/ Maybe
types in ML family languages such as Standard ML, OCaml, Haskell, and Elm. These types from the ML family all have two key features that make them fundamentally different from traditional null
:
-
They are variant types (also known as algebraic types) with two cases: a case that contains a single value, and a case that contains no value.
(Swift calls these two cases
some
andnone
. Some other languages (Haskell, Elm) call themJust
andNothing
. The meaning is the same.) -
The language statically prevents code from working with the value contained in an optional without first ensuring that the optional’s value is
some
instead ofnone
.
All of these ML languages have switch
/ case
constructs that tie variable binding to pattern matching for variant types. Code working with an optional value can match it against some
and none
cases, and the variable that holds the value wrapped inside the some
case will be in scope if and only if the some
pattern matches. This approach allows code to unwrap optional values while receiving the guarantee of (2) above.
[In an actual paper, I would insert example code in an ML language, then show equivalent code using switch/case in Swift]
And what improvements did Swift make on this approach?
The standard switch
/ case
statements are sufficient to work with optional types, but they make common usage patterns verbose and awkward. Swift solves this problem by providing special syntactic sugar for optionals:
- The type syntax
Foo?
, as sugar forOptional<Foo>
. - The literal syntax
nil
, as sugar forOptional.none
. - The
if let
andguard let
statements, which allow conditional execution depending on whether an optional value is present. (These are equivalent to aswitch
/case
on an optional, but more concise.) - The
?.
operator, which short-circuits a property / function chain when anil
appears in the chain. - The
??
operator, which allows code to provide a default value when the left-hand side isnil
. - Automatic wrapping of
x
toOptional.some(x)
when necessary.
While these features are all pure sugar — they add no new capabilities to the the language — they make Swift code that works with optionals substantially easier to read and write than the equivalent code in other ML languages.
[In an actual paper, I would show code samples illustrating all these kinds of sugar in Swift, with the equivalent code in Elm or similar. The paper might then proceed to study how Swift uses optionals in practice, talk about usage successes or barriers to usage, etc.]