Skip to content

Instantly share code, notes, and snippets.

@Kuniwak Kuniwak/Result.swift
Created Oct 19, 2018

Embed
What would you like to do?
public enum Result<T, E> {
case success(T)
case failure(because: E)
public var isSuccess: Bool {
switch self {
case .success:
return true
case .failure:
return false
}
}
public var value: T? {
switch self {
case .success(let value):
return value
case .failure:
return nil
}
}
public var reason: E? {
switch self {
case .success:
return nil
case .failure(because: let reason):
return reason
}
}
}
extension Result: Equatable where T: Equatable, E: Equatable {
public static func ==(lhs: Result<T, E>, rhs: Result<T, E>) -> Bool {
switch (lhs, rhs) {
case (.success(let l), .success(let r)):
return l == r
case (.failure(because: let l), .failure(because: let r)):
return l == r
default:
return false
}
}
}
extension Result: Hashable where T: Hashable, E: Hashable {
public var hashValue: Int {
switch self {
case .success(let value):
return value.hashValue
case .failure(because: let reason):
return reason.hashValue
}
}
}
extension Result: Comparable where T: Comparable, E: Comparable {
public static func <(lhs: Result<T, E>, rhs: Result<T, E>) -> Bool {
switch (lhs, rhs) {
case (.success(let l), .success(let r)):
return l < r
case (.success, .failure):
return true
case (.failure, .success):
return false
case (.failure(because: let l), .failure(because: let r)):
return l < r
}
}
}
extension Result: Sequence {
public typealias Element = T
public typealias Iterator = ResultIterator<T, E>
public func makeIterator() -> Iterator {
return ResultIterator<T, E>(iterating: self)
}
}
public struct ResultIterator<T, E>: IteratorProtocol {
public typealias Element = T
private var result: Result<Element, E>?
public init(iterating result: Result<Element, E>) {
self.result = result
}
public mutating func next() -> Element? {
guard let result = self.result else { return nil }
switch result {
case .success(let value):
self.result = nil
return value
case .failure:
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.