As you may have gathered, I have found an interest in Swift. I have always found it easier to pick up new languages by comparing it to the one I know best, Java.
Please note, this series is intended for experienced Java Developers. I will not go into details of Java or its API. Where sensible I will provide relevant links.
Tony Hoare, inventor of null (aka nil), famously proclaimed it to be his “…billion dollar mistake”. This should not be interpreted as null/nil being evil per se, denoting the absence/not-existence of a value is essential for data processing, but rather the absence of sensible language features to handle null/nil values.
To fully appreciate this you have to jump a couple of sentences further: “… More recent programming languages like Spec# have introduced declarations for non-null references. This is the solution, which I rejected in 1965.”
Unlike Java, Optional is an integral part of Swift language. In Swift variables may not be assigned nil (null), either they have to be initialized with a value or declared as an ? optional.
var nonNill: String = "Foo" //may not be nil var optNil: String? //optional may contain nil var optNonNill: String? = "Bar" //Bar wrapped in an optional
Any attempt to assign a non-optional variable with a nil value results in a compilation error.
Continue reading Swift for Beans – about null, nil and Optional.orElse(“?!”)