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)}

Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE
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 {}

Preparing for a technical iOS job interview
Check out my new book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift & Objective-C, SwiftUI & UIKit, Combine, HTTP Networking, Authentication, Core Data, Concurrency with async/await, Security, Automated Testing and more.
LEARN MORE
Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips