Allow use of concrete associated type of protocols

Swift is all about clarity at the point of use, and its type system is designed in service of that. Type aliases and associated types in particular allow code to use broader types like Int without making it difficult to quickly ascertain meaning.

As an example:

struct Customer: Identifiable {
  let id: Int
}

enum VIP: Customer.ID {
  case johnDoe = 42
}

This has no effect on the compiled code, of course, as Customer.ID is resolved to Int. Even so, it makes it much easier to understand what VIP is: a list of customer IDs.

But now consider this variation:

protocol Customer: Identifiable where ID == Int { }

// ERROR: Associated type 'ID' can only be used with a concrete type or generic parameter base
enum VIP: Customer.ID {
  case johnDoe = 42
}

What changed? It remains impossible for Customer.ID to not be Int, but the compiler is suddenly unwilling to use them interchangeably.

I think this should be rectified in the name of clarity at the point of use: if the associated type of a protocol is constrained to a concrete type, it should be possible to use it as a nested type alias.

11 Likes