I'm working with a library which defines two protocols, A
, and B
, each with its associatedtype
T
, like this:
protocol A {
associatedtype T
}
protocol B {
associatedtype T
}
The two protocols are not coupled on T, and so in theory a third protocol could inherit from both A
and B
, typealias
ing each T
to a different type. Unfortunately, I can't get Swift to distinguish between the two T
s. I tried something like:
protocol C: A, B {
typealias A.T = String
typealias B.T = String
}
but this is not supported syntax. Is there a way to get around this?
This has been discussed in Multiple protocols associatedtype name collision in the Swift forum. Xiaodi Wu writes:
It is very much possible, but the identically named associated types must be, in the conforming type, fulfilled by the same type.
In the future, there may be syntax added to allow types to conform to two protocols with such clashing requirements, but it adds great complexity in terms of implementation and is not without its own pitfalls for users (for example, it can get very confusing for end users of your type).
So a type can conform to both A
and B
with identical associated type T
, e.g.
struct Foo: A, B {
typealias T = String
}
and a protocol can inherit from both A
and B
and restrict T
to the identical type:
protocol C: A, B where T == String {
}
Conforming to both protocols with distinct associated types is currently not supported.