Swift Language Getting started with Swift Language Optional Value and Optional enum


Example

Optionals type, which handles the absence of a value. Optionals say either "there is a value, and it equals x" or "there isn't a value at all".

An Optional is a type on its own, actually one of Swift’s new super-powered enums. It has two possible values, None and Some(T), where T is an associated value of the correct data type available in Swift.

Let's have a look at this piece of code for example:

let x: String? = "Hello World"

if let y = x {
   print(y)
}

In fact if you add a print(x.dynamicType) statement in the code above you'll see this in the console:

Optional<String>

String? is actually syntactic sugar for Optional, and Optional is a type in its own right.

Here's a simplified version of the header of Optional, which you can see by command-clicking on the word Optional in your code from Xcode:

enum Optional<Wrapped> {

 /// The absence of a value.
 case none

 /// The presence of a value, stored as `Wrapped`.
 case some(Wrapped)
}

Optional is actually an enum, defined in relation to a generic type Wrapped. It has two cases: .none to represent the absence of a value, and .some to represent the presence of a value, which is stored as its associated value of type Wrapped.

Let me go through it again: String? is not a String but an Optional<String>.The fact that Optional is a type means that it has its own methods, for example map and flatMap.