October 13, 2020Nil coalescing for optionals in debug prints
To make it easier to use Optionals with string interpolation in debug prints in Swift, we can define our own operator that lets us use a String as default value independent of the Optional type.
infix operator ???: NilCoalescingPrecedence
func ???<T>(
optionalValue: T?,
defaultValue: @autoclosure () -> String
) -> String {
optionalValue
.map { String(describing: $0) } ?? defaultValue()
}
var url: URL?
url = URL(string: "https://example.com")
print("The URL is \(url ??? "nil")")
Black Friday 2024 offer: 30% off!$35$25
100+ tips to take your Swift code to the next level
Swift Gemsby Natalia Panferova
- Advanced Swift techniques for experienced developers bypassing basic tutorials
- Curated, actionable tips ready for immediate integration into any Swift project
- Strategies to improve code quality, structure, and performance across all platforms
Black Friday 2024 offer: 30% off!100+ tips to take your Swift code to the next level
Swift Gems
by Natalia Panferova
$35$25If you are enjoying our blog and would like to support us, you can sponsor us on GitHub.
For updates about the blog and development tips, follow us on X @nilcoalescing.