Skip to content

Instantly share code, notes, and snippets.

@pixelspark
Created June 3, 2015 18:02
Show Gist options
  • Save pixelspark/996153d03acb3608003e to your computer and use it in GitHub Desktop.
Save pixelspark/996153d03acb3608003e to your computer and use it in GitHub Desktop.
Swift Fallible type
/**
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