Custom unwrapper
The Optional
type is an enumeration with two cases. .none
is equivalent to the nil
literal. .some(Wrapped)
stores a wrapped value. You must unwrap the value of an Optional
before you can use it.
Common ways to unwrap an Optional
safely are:
- Optional Binding:
if let ...
- Optional Chaining:
if one?.two?...
- Nil-Coalescing:
let a: Int = optional ?? 0
- Unconditional Unwrapping:
let number = Int("42")!
Another method to safely unwrap an Optional
is a combination of extension
and Nil-Coalescing. Here is a simple extension which allows us to safely unwrap String
:
extension Optional where Wrapped == String {
var unwrapped: String {
return self ?? ""
}
}
let a: String?
if a.unwrapped.isEmpty == 0 {
print("Oh, no! It's empty!")
}