Skip to content

Instantly share code, notes, and snippets.

@zakbarlow1995
Last active September 5, 2019 16:06
Show Gist options
  • Save zakbarlow1995/3ca2f31562cf72eb576ab92ccd7b58e3 to your computer and use it in GitHub Desktop.
Save zakbarlow1995/3ca2f31562cf72eb576ab92ccd7b58e3 to your computer and use it in GitHub Desktop.
Handy quality of life infix operator for string interpolation of optionals
infix operator ???: NilCoalescingPrecedence
public func ??? <T>(optional: T?, defaultValue: @autoclosure () -> String) -> String {
return optional.map { String(describing: $0) } ?? defaultValue()
}
@zakbarlow1995
Copy link
Author

Source: "Using optionals in string interpolation segments can lead to surprising or unwanted results. I defined a custom operator that lets me provide a default string value for optionals that are nil."

Usage:

var someValue: Int? = 5
print("The value is \(someValue ??? "unknown")")
// → "The value is 5"

someValue = nil
print("The value is \(someValue ??? "unknown")")
// → "The value is unknown"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment