Skip to content

Instantly share code, notes, and snippets.

@dimitris-c
Last active April 24, 2018 10:33
Show Gist options
  • Save dimitris-c/9057e636d23f89da1dfbf39929111387 to your computer and use it in GitHub Desktop.
Save dimitris-c/9057e636d23f89da1dfbf39929111387 to your computer and use it in GitHub Desktop.
A generic Either structure.
public enum Either<L, R> {
case left(L)
case right(R)
}
extension Either {
public var left: L? {
switch self {
case .left(let value): return value
default: return nil
}
}
public var right: R? {
switch self {
case .right(let value): return value
default: return nil
}
}
public var isLeft: Bool {
switch self {
case .left: return true
case .right: return false
}
}
public var isRight: Bool {
switch self {
case .left: return false
case .right: return true
}
}
public func either<U>(ifLeft: (L) -> U, ifRight: (R) -> U ) -> U {
switch self {
case .left(let value): return ifLeft(value)
case .right(let value): return ifRight(value)
}
}
}
extension Either {
public static func toLeft(value: L) -> Either {
return .left(value)
}
public static func toRight(value: R) -> Either {
return .right(value)
}
public static func toLeft(values: [L]) -> [Either] {
return values.map(toLeft)
}
public static func toRight(values: [R]) -> [Either] {
return values.map(toRight)
}
public static func lefts(_ array: [Either]) -> [L] {
return array.flatMap { $0.left }
}
public static func rights(_ array: [Either]) -> [R] {
return array.flatMap { $0.right }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment