Created
March 18, 2016 11:08
-
-
Save elm4ward/ca69c7114926ff9c72ec to your computer and use it in GitHub Desktop.
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
/// the protocol | |
protocol ImplicitDefault { | |
static var implicitDefault: Self { get } | |
} | |
/// the implementation for Strings | |
extension String: ImplicitDefault { | |
/// i dont care i take the empty string as default | |
static var implicitDefault: String { return "" } | |
} | |
/// kinda forced unwrap operator | |
postfix operator ~! {} | |
/// postfix function for the ImplicitDefault Optional | |
postfix func ~! <T: ImplicitDefault>(lhs: T?) -> T { | |
guard let t = lhs else { return T.implicitDefault } | |
return t | |
} | |
let s1: String? = nil | |
let s2: String? = "a" | |
let r1 = s1~! + s2~! | |
// -> "a" | |
let r2 = (s1 ?? "") + (s2 ?? "") | |
// -> "a" | |
struct A { | |
let a: String? | |
} | |
let a1 = A(a: nil) | |
let a2 = A(a: nil) | |
let r3 = a1.a~! + a2.a~! | |
// -> "" | |
let r4 = (a1.a ?? "") + (a2.a ?? "") | |
// -> "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment