Last active
August 29, 2015 14:04
-
-
Save hooman/c90d719328d3b11f07c6 to your computer and use it in GitHub Desktop.
Unwrap convenience 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
// Playground - noun: a place where people can play | |
// NOTE: Now that Swift has ?? operator, this gist is mostly obsolete. | |
protocol HasNaturalDefault | |
{ class var naturalDefault:Self {get} } | |
operator postfix ~! {} | |
operator infix ~! {associativity none precedence 170} | |
@postfix func ~! <T:HasNaturalDefault> (lhs: T?) -> T | |
{ return lhs ? lhs! : T.naturalDefault } | |
@infix func ~! <T> (lhs: T?, rhs: T) -> T | |
{ return lhs ? lhs! : rhs } | |
extension Array : HasNaturalDefault { | |
static var naturalDefault:Array { return [ ] } | |
} | |
extension Bool: HasNaturalDefault { | |
static var naturalDefault:Bool { return false } | |
} | |
extension Dictionary : HasNaturalDefault { | |
static var naturalDefault:Dictionary { return [ : ] } | |
} | |
extension Double: HasNaturalDefault { | |
static var naturalDefault:Double { return 0.0 } | |
} | |
extension Int: HasNaturalDefault { | |
static var naturalDefault:Int { return 0 } | |
} | |
extension String: HasNaturalDefault { | |
static var naturalDefault:String { return "" } | |
} | |
// Samples with optionals: | |
var a:[Int]?, b:Bool?, d:[String:Int]?, x:Double?, i:Int?, s:String? | |
a~! | |
b~! | |
d~! | |
x~! | |
i~! | |
s~! | |
a~![1,2,3] | |
b~!true | |
d~!["Key":1] | |
x~!3.1415927 | |
i~!666 | |
s~!"Joe" | |
// Works with implicitly unwrapped optionals, too: | |
var a1:[Int]!, b1:Bool!, d1:[String:Int]!, x1:Double!, i1:Int!, s1:String! | |
a1~! | |
b1~! | |
d1~! | |
x1~! | |
i1~! | |
s1~! | |
a1~![1,2,3] | |
b1~!true | |
d1~!["Key":1] | |
x1~!3.1415927 | |
i1~!666 | |
s1~!"Joe" | |
// Even this works: | |
return x~!2.0*y~!-2.0/z~!2.0 | |
// But It is better to write as: | |
return x~!2.0 * y~!-2.0 / z~!2.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment