NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. Lear more...
Quick Tip Icon
Quick Tip

Nil 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?

// assign a URL some time later
url = URL(string: "https://example.com")

print("The URL is \(url ??? "nil")")
Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Check out our new book!

Swift Gems

100+ tips to take your Swift code to the next level

Swift Gems

100+ tips to take your Swift code to the next level

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift