CocoaPods trunk is moving to be read-only. Read more on the blog, there are 11 months to go.

EitherSwift 0.1.0

EitherSwift 0.1.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Apr 2015
SPMSupports SPM

Maintained by to4iki.



EitherSwift

Represents a value of one of two possible types (a disjoint union.)
Instances of Either are either an instance of Left or Right.

Description

Swift Either type like scala.util.Either
++ some in \/ - scalaz.\/

Take Right Projection is decided it would be want.

Usage

struct Error {
    var reason: String
    init(_ reason: String) { self.reason = reason }
}
let resultL = Either<Error, String>.left(Error("failed"))
let resultR = Either<Error, String>.right("ok")

isLeft / isRight

resultR.isRight // true
resultR.isLeft  // false

swap(~)

~Either<String, String>.left("failed") ?? "fallback" // failed

getOrElse(??)

// Alias for Right Projection.getOrElse
resultL ?? "fallback" // fallback
resultR ?? "fallback" // success

orElse(|||)

// Right Projection
resultL ||| "ok" // .Right("ok")
Either<Error, String>.left(Error("failed1")) ||| resultL ||| resultR // .Right("ok")

map

// Alias for Right Projection.map
resultR.map { "\($0)!" } // .Right("ok!")
resultL.map { "\($0)!" } // .Left(Error("failed"))

flatMap(>>-)

func isFull<T>(string: String) -> Either<T, Bool> {
    return .right(!string.isEmpty)
}

(resultL >>- isFull).fold(
    { e in e.reason},
    { s in s.description }
)
// failed

(resultR >>- isFull).fold(
    { e in e.reason},
    { s in s.description }
)
// true

Methods

Either<A, B>

  • Instance Methods
    • fold<X>(fa: A -> X, _ fb: B -> X) -> X
    • swap() -> Either<B, A>
    • getOrElse(or: () -> B) -> B Right Projection
    • orElse(or: () -> B) -> Either<A, B> Right Projection
    • orElse(or: () -> Either<A, B>) -> Either<A, B> Right Projection
    • map<X>(f: B -> X) -> Either<A, X> Right Projection
    • flatMap<X>(f: B -> Either<A, X>) -> Either<A, X> Right Projection

  • Class Methods
    • left(value: A) -> Either<A, B>
    • right(value: B) -> Either<A, B>
    • cond<A, B>(test: Bool, right: () -> B, left: () -> A) -> Either<A, B>

LeftProjection<A, B>

  • Instance Methods
    • getOrElse(or: () -> A) -> A
    • foreach<U>(f: A -> U)
    • forall(f: A -> Bool) -> Bool
    • exists(f: A -> Bool) -> Bool
    • map<X>(f: A -> X) -> Either<X, B>
    • flatMap<X>(f: A -> Either<X, B>) -> Either<X, B>
    • filter(p: A -> Bool) -> Either<A, B>?
    • toOption() -> A?

RightProjection<A, B>

  • Instance Methods
    • getOrElse(or: () -> B) -> B
    • foreach<U>(f: B -> U)
    • forall(f: B -> Bool) -> Bool
    • exists(f: B -> Bool) -> Bool
    • map<X>(f: B -> X) -> Either<A, X>
    • flatMap<X>(f: B -> Either<A, X>) -> Either<A, X>
    • filter(p: B -> Bool) -> Either<A, B>?
    • toOption() -> B?

Installation

Licence

MIT

Author

to4iki