I'm trying to do something along the lines of this:
protocol Protocol {
associatedtype T
associatedtype ArrayT = Array<T>
}
struct Struct<ProtocolType: Protocol> {
func doSomething(with: ProtocolType.ArrayT) {
let _ = with.map { $0 }
// ^ compiler complains on this line
// "value of type ProtocolType.ArrayT has no member map"
}
}
where I define a convenience typealias ArrayT
that uses the associatedtype
T
. It seems that when I try to use ArrayT
like in doSomething(_:)
, I lose the Array
type information of ArrayT
.
Shouldn't ArrayT
definitely be an Array
and therefore a member of the Sequence
protocol, exposing the map
function?
When you "initialize" an
associatedtype
, you're not defining it. That's not the point of associated types in the first place. Associated types are deliberately unbound ("placeholders") until the adopting class resolves them all. All you're doing there is giving it a default value, which a conforming class is allowed to override. To extend your example:For your example, it seems all you really want is to declare
with: Array<ProtocolType.T>
(or simplywith: [ProtocolType.T]
) as the parameter type.The line
associatedtype ArrayT = Array<T>
only tells the compiler that the default value ofArrayT
isArray<T>
. An adaption of the protocol can still changeArrayT
like:If you want a fixed type, you should use a typealias...
But the compiler complains that the type is too complex