Created
July 15, 2014 13:13
-
-
Save ilyannn/bb8157b76743a1e4fb40 to your computer and use it in GitHub Desktop.
Unwrapping a bunch of optionals
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
class Unwrapper<T, R> { | |
let failed:R? | |
let values:[T] | |
init(values: [T] = [], failed:R? = nil) { | |
self.values = values | |
self.failed = failed | |
} | |
class func unwrap(value:T?, elseReturn safe:R) -> Unwrapper<T, R> { | |
return Unwrapper().unwrap(value, elseReturn:safe) | |
} | |
func unwrap(value:T?, elseReturn safe:R) -> Unwrapper<T, R> { | |
if failed { | |
return self | |
} | |
if let really = value { | |
var newValues = self.values | |
newValues += really | |
return Unwrapper(values: newValues) | |
} | |
return Unwrapper(failed: safe) | |
} | |
func andThen3(then3:(T, T, T) -> R) -> R { | |
if let failed_ = failed { | |
return failed_ | |
} | |
return then3(values[0], values[1], values[2]) | |
} | |
func unwrap(value:T?, elseReturn safe:R, andThen3 then3: (T, T, T) -> R) -> R { | |
return unwrap(value, elseReturn: safe).andThen3(then3) | |
} | |
} | |
func test(a:Int?, b:Int?, c:Int?) -> String { | |
return Unwrapper | |
.unwrap(a, elseReturn:"-") | |
.unwrap(b, elseReturn:"--") | |
.unwrap(c, elseReturn:"---") | |
{ (a, b, c) in | |
"\(a)\(b)\(c)" | |
} | |
} | |
test(nil, nil, nil) // - | |
test( 1, nil, 3) // -- | |
test( 1, 2, nil) // --- | |
test( 1, 2 , 3) // 123 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment