June 2, 2014

Apple announced the Swift programming language during this morning’s WWDC. It was lots of fun to read through the five hundred page documentation on iBooks. I am very impressed with how elegantly Apple incorporated functional programming concepts and am very excited about what mainstream adoption of Swift will mean for functional programming.

There is a lot to like about Swift, but my favorite is that only variables explicitly marked as nillable can be assigned a null value. Normal variables cannot be null and accesses to nillable variables have to explicitly unwrap the nil value with a ! or chained with ?.

“nil cannot be used with non-optional constants and variables. If a constant or variable in your code needs to be able to cope with the absence of a value under certain conditions, always declare it as an optional value of the appropriate type.”

Swift will be the first mainstream language to adopt this requirement and I hope that other languages will follow its lead. Null pointer exceptions have been a huge pain point of any statically typed or dynamically typed language. Tony Hoare, the inventor of null, considers his own invention a “billion dollar mistake”.

In Swift a nil is value like any other, backed by a real memory location. This effectively eliminates the traditional null pointer exception. The compiler forces the developer to use an if statement to handle both the nil and non-nil cases when access the nillable variable. Scala and Haskell take a similar approach with the Option/Maybe monad.

“Swift’s nil is not the same as nil in Objective-C. In Objective-C, nil is a pointer to a non-existent object. In Swift, nil is not a pointer—it is the absence of a value of a certain type. Optionals of any type can be set to nil, not just object types.” - The Swift Programming Language.

This distinction is important since nil is no longer a special case within the language as an absence of a value, it is simply another value.

Kudos to Swift team for making this bold decision.

736 Kudos