Last active
August 29, 2015 14:16
-
-
Save brocoo/1fa4972d0a060899119c to your computer and use it in GitHub Desktop.
A result enum, storing a boxed type or a NSError meant to be return from any process (API call, etc) (Swift 1.2)
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
// MARK: - Box | |
final public class Box<T> { | |
public let unbox:T | |
public init(_ value: T) { self.unbox = value } | |
} | |
// MARK: - Result enum | |
public enum Result<T: Printable> { | |
case Success(Box<T>) | |
case Failure(NSError) | |
case Pending | |
public init(_ value: T) { | |
self = .Success(Box(value)) | |
} | |
public init(_ error: NSError) { | |
self = .Failure(error) | |
} | |
public var value: T? { | |
switch self { | |
case .Success(let value): return value.unbox | |
default: return nil | |
} | |
} | |
public func transform<P>(f: T -> Result<P>) -> Result<P> { | |
switch self { | |
case Success(let value): return f(value.unbox) | |
case Failure(let error): return .Failure(error) | |
case Pending: return .Pending | |
} | |
} | |
public func transform<P>(f: T-> Result<P>, queue: dispatch_queue_t, completion: Result<P> -> Void) { | |
switch self { | |
case .Success(let value): | |
dispatch_async(queue, { () -> Void in | |
let result = f(value.unbox) | |
dispatch_async(dispatch_get_main_queue()) { () -> Void in | |
completion(result) | |
} | |
}) | |
case Failure(let error): completion(.Failure(error)) | |
case Pending: completion(.Pending) | |
} | |
} | |
} | |
extension Result: Printable, DebugPrintable { | |
public var description: String { | |
switch self { | |
case .Success(let value): return value.unbox.description | |
case .Failure(let error): return error.description | |
case .Pending: return "Pending" | |
} | |
} | |
public var debugDescription: String { return self.description } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment