I have always preferred explicitly typed languages, saving a couple of characters by simply declaring a variable as var or let can quickly end up in a game of “Guess who?” or “what” to be more precise.
Its straight forward enough with immediate assignments or when the expected type is clear.
var name = "Foo" //clearly String
var street = customer.street //most likely String
var customer = Customer(name: "Foo", ...)
However when dealing with complex domain models or business functions with unclear return type the value of strong typing quickly becomes apparent.
var value = contract.amount //Int/UInt/Float/Double/String/...?
var customer = contract.customer //String/domain model Customer/...?
var amountDue = billingService.calculate(...) //Int/UInt/Float/Double/...?
Continue reading Swift for Beans – var, let and Type Inference →
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(“?!”) →