Logo for tanaschita.com

Extending optionals in Swift

Quick tip on how to extend an optional in Swift

16 May 2021 · 2 min read

As we have learned in Understanding Swift Optionals, an optional is just an enum of two cases.

enum Optional<Wrapped> {
/// The absence of a value.
case none
/// The presence of a value, stored as `Wrapped`.
case some(Wrapped)
}

Knowing this, we can extend an optional just like any other type.

extension Optional where Wrapped == String {
var isNilOrEmpty: Bool {
return self?.isEmpty ?? true
}
}

In the example above, we are extending an optional String by adding where Wrapped == String to our extension.

Now, we can use the computed property isNilOrEmpty on every optional String.

var name: String?
if name.isNilOrEmpty {
}

Related tags

Written by