Skip to content

Instantly share code, notes, and snippets.

@acalism
Created February 2, 2018 14:07
Show Gist options
  • Save acalism/facf63b57494e60468154561580a2524 to your computer and use it in GitHub Desktop.
Save acalism/facf63b57494e60468154561580a2524 to your computer and use it in GitHub Desktop.
How to print Optional<Wrapped>
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