Skip to content

Instantly share code, notes, and snippets.

@kirsteins
Created April 30, 2015 08:54
Show Gist options
  • Save kirsteins/a5cbfc48a9a451359856 to your computer and use it in GitHub Desktop.
Save kirsteins/a5cbfc48a9a451359856 to your computer and use it in GitHub Desktop.
Result
public class Box<T> {
public let value: T
public init(_ value: T) {
self.value = value
}
}
public enum Result<T> {
case Success(Box<T>)
case Failure(NSError)
public init(value: T) {
self = Success(Box(value))
}
public init(error: NSError) {
self = Failure(error)
}
public var value: T? {
switch self {
case let .Success(box):
return box.value
default:
return nil
}
}
public var error: NSError? {
switch self {
case let .Failure(error):
return error
default:
return nil
}
}
}
public extension Result {
public func map<U>(f: T -> U) -> Result<U> {
switch self {
case let .Success(box):
return Result<U>.Success(Box(f(box.value)))
case let .Failure(error):
return Result<U>.Failure(error)
}
}
public func flatMap<U>(f: T -> Result<U>) -> Result<U> {
return Result.flatten(map(f))
}
public static func flatten<T>(result: Result<Result<T>>) -> Result<T> {
switch result {
case let .Success(innerResult):
return innerResult.value
case let .Failure(error):
return Result<T>.Failure(error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment