[swift-users] typealias in a protocol: can only be used as generic constraint?
jens at mooseyard.com
Tue Dec 29 02:05:38 CST 2015
> On Dec 28, 2015, at 3:43 PM, Jonathan Bailey via swift-users <swift-users at swift.org> wrote:
> In the following code, I get an error on the line indicated (4th from the bottom) that "Protocol 'APIEndPoint' can only be used as a generic constraint because it has Self or associated type requirements” I understand this is because the APIEndPoint protocol contains a type alias. However I don’t understand why this means it can’t be used as a type?
I finally understand the reason, after reading [a draft of] objc.io's Advanced Swift book. You can’t use such a protocol as a type because if the aliased type appears in the API, it won’t be consistent between different objects that conform to the protocol but have different aliased types. For example, if a protocol Foo has a method foo() that returns a typealias T, then different objects conforming to Foo will return different types from their foo() methods, so there’s no type-safe way to represent that return value.
In your case you’ve got a typealias but you’re not using it in the protocol’s API. It looks like it’s just internally used inside the implementation of the urlString method. You can probably change your code around to get the same effect without using a typealias. Make baseURL a regular non-static method of API, then just have a property of APIEndpoint of type API.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the swift-users