Last active
April 24, 2018 10:33
-
-
Save dimitris-c/9057e636d23f89da1dfbf39929111387 to your computer and use it in GitHub Desktop.
A generic Either structure.
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 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