Created
January 2, 2017 10:17
-
-
Save vjosullivan/902374902da9872764c0840e4cb2bd48 to your computer and use it in GitHub Desktop.
??? - A custom optional -> string coalescing operator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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