June 04th   2014

Swift: All variables must be initialised

  iOS , Swift

A major change from Objective-C is that all variables must hold a value (i.e. must be initialised). We get an error if we try to declare a variable without initialising it.

var s: String

println(s)

The compiler will return:

Variable 's' used without being initialized

Therefore, one must initialise variable as they are declared:

var s: String = "WWDC2014"

Or, since the type is inferred from the value:

var s = "WWDC2014"

However, a variable can be explicitly declared as nil-able: being able to store a value of certain type or nil. And since it's optional, we don't have to assign a value but we need to specify the type.

var s: String?

s will now have the value of nil - which is different from the null we had in Objective-C. In Swift, nil means nothing as in the lack of a value.


«         »

Web Analytics