SE-0309: Unlock existential types for all protocols

The point is that Bar in this example has associated type and static requirements, which means, an existential of type Bar cannot conform to Bar because the compiler will have no way to know what the associated type actually is, or where the implementations of the static methods are to be found.

struct Foo<T: Bar> requires some type T that conforms to Bar, but existentials of Bar can never conform to Bar. Therefore let foo = Foo(bar: bar()) can never compile.

That's why the "any" syntax doesn't seem viable to me, because any Bar makes it sound like the compiler statically knows that this function returns an existential container whose type is statically known to conform to Bar, which it doesn't and can't because Bar has associated type and static requirements.

With the expanded rules about existentials, perhaps we could have a protocol-type object of type Bar (the existential container type), however that object can't enjoy self-conformance because the compiler can't infer the existential type within the existential container at compile-time. It's a logical impossibility sadly.

The usual kind of proof that's given for this is a reduction to absurdity. (Forgive me if I butcher this)

Given:

protocol Bar {
    associatedtype X
    static var x: X { get }
    init()
}

class A: Bar {
    typealias X = Int
    static var x: Int = 42
    init() {}
}

class B: Bar {
    typealias X = String
    static var x: String = "blah"
    init() {}
}

... and a function that returns "any Bar" ...

func bar() -> any Bar { .random() ? A() : B() }

If the statically known type "any Bar" conforms to Bar protocol, then we reach absurdity:

struct Foo<T: Bar> {
    var bar: T
}

let bar = Foo(bar: bar()).bar // what's the static type of bar?

func impossible<T: Bar>(_:T) { print(T.x) }

impossible(bar)
// what gets printed, according to the compiler? 

But I probably butchered it. I think there was a better example given by @xwu on this thread: Very confused about some compiler warnings related to protocols—bugs or intended?

1 Like