[Re-Proposal] Type only Unions

Given

protocol P {
    associatedtype A
    func foo() -> A
}
struct S: P { … }
struct R: P { … }

func g<T: P>(_ x: T)
struct W<T: P> {}

I would expect the following work:

let x: S | R = S()
let y: any P = x
let z = x.foo() // typed as S.A | R.A
g(x) // Because of SE-0352

But not W<S | R>.

If one needs to write generic code, where generic type parameter can be satisfied by S, R, any P and S | R, then
existential subtyping as generic constraint is needed.

Actually for x.foo() to work, even common protocol is not needed:

struct A {
    func foo() -> Int { ... }
    func bar(_ x: Int) { ... }
}
struct B {
    func foo() -> String { ... }
    func bar(_ x: String) { ... }
}

let x: A | B = A()
let y = x.foo() // ok, typed as Int | String.
x.bar(y) // error
1 Like