Optional Value and Optional enum
suggest changeOptional is the type that handles the absence of a value. An optional says either “there is a value, and it equals x” or “there isn’t a value at all”.
An optional is a type of its own, implemented as an enum. It has two cases, .none and .some(T), where T is the associated value.
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 print(x.dynamicType) in the code above, the console shows the type below. Swift 3 and later use type(of: x) instead of the dynamicType property:
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.
String? is not a String. It is an Optional<String>. Because Optional is a type, it has its own methods, including map and flatMap.