Since the above answers clearly explains how to play safely with Optionals. I will try explain what Optionals are really in swift.
Another way to declare an optional variable is
var i : Optional<Int>
And Optional type is nothing but an enumeration with two cases, i.e
enum Optional<Wrapped> : ExpressibleByNilLiteral {
case none
case some(Wrapped)
.
.
.
}
So to assign a nil to our variable 'i'. We can do
var i = Optional<Int>.none
or to assign a value, we will pass some value
var i = Optional<Int>.some(28)
According to swift, 'nil' is the absence of value.
And to create an instance initialized with nil
We have to conform to a protocol called ExpressibleByNilLiteral
and great if you guessed it, only Optionals
conform to ExpressibleByNilLiteral
and conforming to other types is discouraged.
ExpressibleByNilLiteral
has a single method called init(nilLiteral:)
which initializes an instace with nil. You usually wont call this method and according to swift documentation it is discouraged to call this initializer directly as the compiler calls it whenever you initialize an Optional type with nil
literal.
Even myself has to wrap (no pun intended) my head around Optionals :D Happy Swfting All.