Skip to content

Instantly share code, notes, and snippets.

@wjlafrance
Last active August 29, 2015 14:18
Show Gist options
  • Save wjlafrance/ee2cd2b8934e18749975 to your computer and use it in GitHub Desktop.
Save wjlafrance/ee2cd2b8934e18749975 to your computer and use it in GitHub Desktop.
Result<T,U> working in Xcode 6.3
//: 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)") }
@wjlafrance
Copy link
Author

Playground execution failed: OptionalStuff.playground:12:1: warning: code after 'return' will never be executed
}
^
integer overflows when converted from 'Builtin.Int32' to 'Builtin.Int8'OptionalStuff.playground:5:6: error: unimplemented IR generation feature non-fixed multi-payload enum layout
enum Result<T, U> {
^

@wjlafrance
Copy link
Author

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