This is a Swift microframework providing Either<Left, Right> and EitherProtocol, with generic implementations of ==/!= where Left & Right: Equatable.
Either allows you to specify that a value should be one of two types, or that that a value of a single type should have one of two semantics. For example, Either<Int, NSError> might be the result of a computation which could fail, while Either<String, String> might mean that you want to handle a string in one of two different ways.
EitherProtocol is an easy-to-adopt protocol (it requires one method and two constructor functions) which allows clients to generically use Either or conforming Result, etc. types.
Constructing an Either:
// Wrap:
letleft=Either<Int,String>.left(4)letright=Either<Int,String>.right("four")Extracting the value:
// Unwrap:
letvalue= left.either(ifLeft:{ $0 }, ifRight:{ $0.characters.count })Representing success/failure:
letresult=someComputation() // result has type `Either<Error, T>`
letsuccess= result.right // success has type `T?`
leterror= result.left // error has type `Error?`However, you might instead prefer to use a more tailored Result type. Even if it doesn’t conform to EitherProtocol already, you can implement conformance in your application:
extensionResult:EitherProtocol{ // Result<T, Error>
staticfunc toLeft(_ value:Error)->Result{returnResult(error: value)}staticfunc toRight(value:T)->Result{returnResult(value: value)}func either<Result>(ifLeft:(Error)->Result, ifRight:(T)->Result)->Result{switchself{caselet.success(x):returng(x)caselet.failure(error):returnf(error)}}}Now you can use generic functions like ==, !=, and any you might write with both Either and Result.
API documentation is in the source.
- Add this repository as a submodule and check out its dependencies, and/or add it to your Cartfile if you’re using carthage to manage your dependencies.
- Drag
Either.xcodeprojinto your project or workspace, and do the same with its dependencies (i.e. the other.xcodeprojfiles included inEither.xcworkspace). NB:Either.xcworkspaceis for standalone development of Either, whileEither.xcodeprojis for targets using Either as a dependency. - Link your target against
Either.frameworkand each of the dependency frameworks. - Application targets should ensure that the framework gets copied into their application bundle. (Framework targets should instead require the application linking them to include Either and its dependencies.)
Or use the Swift package manager and add this to you Package.swift file:
...
dependencies: [
... .package(url: "https://github.com/robrix/Either", "2.0.1" ..< "3.0.0")
],
targets: [
...
.target(
name: "<YourTargetName>",
dependencies: ["Either"]),
]