Skip to content

Instantly share code, notes, and snippets.

@vjosullivan
Created January 2, 2017 10:17
Show Gist options
  • Save vjosullivan/902374902da9872764c0840e4cb2bd48 to your computer and use it in GitHub Desktop.
Save vjosullivan/902374902da9872764c0840e4cb2bd48 to your computer and use it in GitHub Desktop.
??? - A custom optional -> string coalescing operator
// Source: https://oleb.net/blog/2016/12/optionals-string-interpolation
infix operator ???: NilCoalescingPrecedence
/// Provides a String default value for an Optional of any type.
/// Overcomes the problem with the `??` operator whare the default value must be
/// of the same type as the left hand side.
public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String {
switch optional {
case let value?: return String(describing: value)
case nil: return defaultValue()
}
}
@vjosullivan
Copy link
Author

The source for this code is: https://oleb.net/blog/2016/12/optionals-string-interpolation

I came across the source in Thomas Hanning's Newsletter (11): https://thomashanning.curated.co/issues/11?#start

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