Created
February 2, 2018 14:07
-
-
Save acalism/facf63b57494e60468154561580a2524 to your computer and use it in GitHub Desktop.
How to print Optional<Wrapped>
This file contains hidden or 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
fileprivate protocol _Optional { | |
func unwrappedString() -> String | |
} | |
extension Optional: _Optional { | |
fileprivate func unwrappedString() -> String { | |
switch self { | |
case .some(let wrapped as _Optional): return wrapped.unwrappedString() | |
case .some(let wrapped): return String(describing: wrapped) | |
case .none: return String(describing: self) | |
} | |
} | |
} | |
postfix operator ~? { } | |
public postfix func ~? <X> (x: X?) -> String { | |
return x.unwrappedString | |
} | |
// example | |
var d: Double? = 12.34 | |
print(d) // Optional(12.34) | |
print(d~?) // 12.34 | |
d = nil | |
print(d~?) // nil | |
let i: Int??? = 5 | |
print(i) // Optional(Optional(Optional(5))) | |
print("i: \(i~?)") // i: 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment