Shorthand conformance to a protocol with a primary associated type


Today I met this compiler error:

protocol MyProtocol<Value> {
    associatedtype Value

// ❌ error: cannot inherit from protocol type with generic argument 'MyProtocol<Int>'
// ❌ error: type 'MyStruct' does not conform to protocol 'MyProtocol'
// ❌ note: protocol requires nested type 'Value'; add nested type 'Value' for conformance
//        associatedtype Value
//                       ^
struct MyStruct: MyProtocol<Int> { }

All right, I get it: the correct program is as below:

protocol MyProtocol<Value> {
    associatedtype Value

struct MyStruct: MyProtocol {
    typealias Value = Int

However, I really wish the first version would compile.

The particular protocol I want to conform to does not require the concrete conforming types to use the associated type in their body, and I thus can't rely on type inference to automatically define the associated type. I do have to write an explicit typealias Value = ... line.

Since this explicit declaration of the associated type can most of the time be avoided, thanks to type inference, it looks like the language is willing to help the developer omit this explicit declaration.

In this context, is it unreasonable to desire that the language would evolve so that the explicit declaration is avoided with the : P<V> syntax?

// Please
struct MyStruct: MyProtocol<Int> { }

What do you think? Is this idea worth a pitch?


Definitely, but I would like to hear what @Slava_Pestov has to say about this.

This is specified in swift-evolution/proposals/ at main · apple/swift-evolution · GitHub and it’s supposed to work, we just haven’t gotten around to it yet, sorry.


Oh, great! A little more patience, then :-) Thank you @ibex10 and @Slava_Pestov

1 Like