Last active
August 29, 2015 14:18
-
-
Save wjlafrance/ee2cd2b8934e18749975 to your computer and use it in GitHub Desktop.
Result<T,U> working in Xcode 6.3
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
//: Playground - noun: a place where people can play | |
import Darwin | |
class Box<T> { | |
let contents: T | |
init(_ contents: T) { self.contents = contents } | |
} | |
enum Result<T, U> { | |
case _Success(Box<T>) | |
case _Failure(Box<U>) | |
static func Success(t: T) -> Result { return ._Success(Box(t)) } | |
static func Failure(u: U) -> Result { return ._Failure(Box(u)) } | |
func onSuccess(action: (T) -> ()) -> Result { | |
switch self { | |
case let ._Success(box): | |
action(box.contents) | |
default: let nop = 0 | |
} | |
return self | |
} | |
func onFailure(action: (U) -> ()) -> Result { | |
switch self { | |
case let ._Failure(box): | |
action(box.contents) | |
default: let nop = 0 | |
} | |
return self | |
} | |
} | |
func doThing() -> Result<String, Int> { | |
return arc4random_uniform(2) == 0 ? .Success("Hello world") : .Failure(42) | |
} | |
doThing().onSuccess { message in println("Success! \(message)") } | |
.onFailure { message in println("Failure! \(message)") } |
Author
wjlafrance
commented
Apr 9, 2015
See older revision for broken version. Regarding the non-fixed multi-payload, the ResultBox type is used.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment