Skip to content

Instantly share code, notes, and snippets.

@danielctull
Last active March 2, 2021 10:37
Show Gist options
  • Save danielctull/0c85c75c31cf20c0c33ed348e3e07976 to your computer and use it in GitHub Desktop.
Save danielctull/0c85c75c31cf20c0c33ed348e3e07976 to your computer and use it in GitHub Desktop.
Trying to see what casting options exist with an Either type.
public enum Either<Left, Right> {
case left(Left)
case right(Right)
}
extension Either {
public func `as`(_ type: Left.Type) -> Left? {
guard case let .left(left) = self else { return nil }
return left
}
public func `as`(_ type: Right.Type) -> Right? {
guard case let .right(right) = self else { return nil }
return right
}
public func `as`<L,R>(_ type: L.Type) -> L? where Left == Either<L,R> {
guard case let .left(left) = self else { return nil }
return left.as(type)
}
public func `as`<L,R>(_ type: R.Type) -> R? where Left == Either<L,R> {
guard case let .left(left) = self else { return nil }
return left.as(type)
}
public func `as`<L,R>(_ type: L.Type) -> L? where Right == Either<L,R> {
guard case let .right(right) = self else { return nil }
return right.as(type)
}
public func `as`<L,R>(_ type: R.Type) -> R? where Right == Either<L,R> {
guard case let .right(right) = self else { return nil }
return right.as(type)
}
}
let either = Either<Either<String, Int>, Either<Float, Double>>.left(.left("Hello"))
print(either.as(String.self))
print(either.as(Int.self))
print(either.as(Float.self))
print(either.as(Double.self))
let either2 = Either<Either<Either<String, Int>, Double>, Float>.left(.left(.left("Hello")))
print(either2.as(String.self)) // Fails to compile (obviously)
print(either2.as(Int.self)) // Fails to compile (obviously)
print(either2.as(Float.self))
print(either2.as(Double.self))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment