Created
April 30, 2015 08:54
-
-
Save kirsteins/a5cbfc48a9a451359856 to your computer and use it in GitHub Desktop.
Result
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
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