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)
}
Sponsorship logo
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 {
}
Sponsorship logo
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

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

swift

basics

Working with Strings in Swift

Learn how to use Swift's String type and its companions Character, Index and Substring.

05 Jun 2021 · 5 min read

Latest articles and tips

© 2023 tanaschita.com

Privacy policy

Impressum