Skip to content

Instantly share code, notes, and snippets.

@a-voronov
Last active January 12, 2017 02:02
Show Gist options
  • Save a-voronov/6a21b23d13116bf6e6d31006a9d408d2 to your computer and use it in GitHub Desktop.
Save a-voronov/6a21b23d13116bf6e6d31006a9d408d2 to your computer and use it in GitHub Desktop.
Since Swift doesn't support covariant Generics yet, the only workaround I see so far is to map value via creating new one through map or flatMap 😿
enum Generic<T> {
case Some(T)
init(_ x: T) {
self = .Some(x)
}
func flatMap<U>(@noescape f: (T) throws -> Generic<U>) rethrows -> Generic<U> {
switch self {
case .Some(let x):
return try f(x)
}
}
func map<U>(@noescape f: (T) throws -> U) rethrows -> Generic<U> {
switch self {
case let .Some(x):
return try .Some(f(x))
}
}
}
protocol A { }
class B : A { }
let b: Generic<B> = .Some(B())
let a1: Generic<A> = b.map { $0 }
let a2: Generic<A> = b.flatMap(Generic.init)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment