-
-
Save joelreymont/a17cf94bf5cda9940324 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
/** | |
FIXME: Box exists to prevent the "Unimplemented IR generation feature non-fixed multi-payload enum layout" error. */ | |
final class Box<T> { | |
let value: T | |
init(_ value: T) { | |
self.value = value | |
} | |
} | |
/** | |
Fallible<T> represents the outcome of an operation that can either fail (with an error message) or succeed (returning an | |
instance of T). */ | |
enum Fallible<T> { | |
case Success(Box<T>) | |
case Failure(String) | |
init<P>(_ other: Fallible<P>) { | |
switch other { | |
case .Success(let s): | |
self = .Success(Box<T>(s.value as! T)) | |
case .Failure(let e): | |
self = .Failure(e) | |
} | |
} | |
init(_ value: T) { | |
self = .Success(Box<T>(value)) | |
} | |
/** | |
If the result is successful, execute `block` on its return value, and return the (fallible) return value of that block | |
(if any). Otherwise return a new, failed result with the error message of this result. This can be used to chain | |
operations on fallible operations, propagating the error once an operation fails. */ | |
func use<P>(@noescape block: T -> P) -> Fallible<P> { | |
switch self { | |
case Success(let box): | |
return .Success(Box<P>(block(box.value))) | |
case Failure(let errString): | |
return .Failure(errString) | |
} | |
} | |
func use<P>(@noescape block: T -> Fallible<P>) -> Fallible<P> { | |
switch self { | |
case Success(let box): | |
return block(box.value) | |
case Failure(let errString): | |
return .Failure(errString) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment