Extension of protocol composition

Is there a roapmap or plan for making it possible to extend a protocol composition (or typealias thereof) directly, rather than having to extend one protocol and use where Self clauses for the rest?

protocol A {}
protocol B {}
typealias C = A & B

extension C {}                 // error
extension A & B {}             // error
extension A where Self: B {}   // valid
extension B where Self: A {}   // valid

It seems reasonable that the compiler could make some arbitrary choice of ordering, perhaps alphabetically by protocol name, and just translate the code extension C into extension A where Self: B.

• • •

This is likely to arise with respect to the Numerics library. People will often want to write algorithms against AlgebraicField & ElementaryFunctions, and the library may end up including a typealias for that combination to facilitate doing so.

Such a typealias will help when defining constraints on generics, but not when writing extension methods. Is this something we can make work?

4 Likes

You can sort of get there by creating a new protocol instead of using a typealias, but I don't know if that has any disadvantages.

protocol A {}
protocol B {}
protocol C: A & B {}

When you do this, types conforming to A And B do not necessarily conform to C.

10 Likes

I think the "proper" way of doing this would be with parametrized extensions, considered in the generics manifesto and my #1 missing feature from Swift:

protocol This {}
protocol That {}
typealias These = This & That

extension <A> A where A: These {}

That would mean that the existential itself won‘t receive any of this. If you upcast your concrete type to These, it won‘t contain any functionality from the extension.

There is another way of viewing this is like so:

// extend only the existential 
extension any These {}

// extension only the conforming types
extension some These {} // same as `extension <T: These> T {}`

// extend conforming types and the existential
extension These {}  
1 Like

While I share your desire for parameterized extensions, I do not think they are necessary for extending a protocol composition.

My bad, you're correct: if an extension like the one I showed was possible, it wouldn't apply to existentials.