According to Differences Between Opaque Types and Boxed Protocol Types in TSPL, you have the following limitation on protocols with associated type.
You can’t use
Container
as the return type of a function because that protocol has an associated type.
Yet, the code in the example that is supposed to fail, actually compiles.
// Error: Protocol with associated types can't be used as a return type.
func makeProtocolContainer<T>(item: T) -> Container {
return [item]
}
Moreover, the last example, with appropriate adjustments, compiles and works "as expected" (assuming, we agree on what's expected).
func makeProtocolContainer<T>(item: T) -> Container {
return [item]
}
let boxedContainer = makeProtocolContainer(item: 12)
let twelve = boxedContainer[0]
print(type(of: twelve))
// Prints "Int"
Here are few questions. Is it an error in the book (this should be a valid code) or in the compiler? If it is an error in the book, has it always been an error, or this restriction (can't be return type of a function on protocols with associated type) has been removed in the later version? If this is the case - what is the corresponding SE proposal?
Thanks.