Skip to content

Instantly share code, notes, and snippets.

@pauljohanneskraft
Last active December 13, 2018 15:34
Show Gist options
  • Save pauljohanneskraft/607134b54af4c37349b7e36cb8baf8e3 to your computer and use it in GitHub Desktop.
Save pauljohanneskraft/607134b54af4c37349b7e36cb8baf8e3 to your computer and use it in GitHub Desktop.
Either

Either

Use Either to allow multiple result types to be combined into one. You can then switch over the specific types to evaluate the result. Either can be used as described below.

let _b = false

func b() -> Either<String, Int> {
    if _b {
        return *""
    } else {
        return *1
    }
}

func test() {
    let c = b()
    c.switch(
        first: { string in

        },
        second: { int in

        }
    )
}
prefix operator *
enum Either<A, B> {
case first(A)
case second(B)
func `as`(_ type: A.Type) -> A? {
guard case let .first(a) = self else {
return nil
}
return a
}
func `as`(_ type: B.Type) -> B? {
guard case let .second(b) = self else {
return nil
}
return b
}
func `switch`<T>(as firstCase: A.Type, _ aFunction: (A) -> T, as secondCase: B.Type, bFunction: (B) -> T) -> T {
switch self {
case let .first(a):
return aFunction(a)
case let .second(b):
return bFunction(b)
}
}
func `switch`<T>(as firstCase: B.Type, _ bFunction: (B) -> T, as secondCase: A.Type, aFunction: (A) -> T) -> T {
switch self {
case let .first(a):
return aFunction(a)
case let .second(b):
return bFunction(b)
}
}
func `switch`<T>(first aFunction: (A) -> T, second bFunction: (B) -> T) -> T {
return self.switch(as: A.self, aFunction, as: B.self, bFunction: bFunction)
}
}
prefix func * <A, B>(lhs: A) -> Either<A, B> {
return .first(lhs)
}
prefix func * <A, B>(rhs: B) -> Either<A, B> {
return .second(rhs)
}
let _b = false
func b() -> Either<String, Int> {
if _b {
return *""
} else {
return *1
}
}
func test() {
let c = b()
c.switch(
first: { string in
},
second: { int in
}
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment