[swift-users] Covariance in protocol adoption

davesweeris at mac.com davesweeris at mac.com
Tue Feb 16 13:54:38 CST 2016


I think it’s something to do with subclasses overriding the method and potentially returning a type that’s different that what the compiler is expecting. Or something like that. 

I hope it gets addressed at some point, though, because it drives me nuts, too.

> On Feb 16, 2016, at 1:47 PM, Diego Sánchez via swift-users <swift-users at swift.org> wrote:
> 
> Hi all,
> 
> Covariance works properly with classes:
> class MyType {}
> class MySubtype: MyType {}
> 
> class MyClass {
>     func createMyType() -> MyType {
>         return MyType()
>     }
> }
> 
> class MySubClass: MyClass {
>     override func createMyType() -> MySubtype {
>         return MySubtype()
>     }
> }
> 
> However it doesn't work for protocol conformance:
> 
> protocol MyProtocol {
>     func createMyType() -> MyType
> }
> 
> class MyConformingClass: MyProtocol {
>     func createMyType() -> MySubtype {
>         return MySubtype()
>     }
> }
> 
> Compiler error for this case:
> error: type 'MyConformingClass' does not conform to protocol 'MyProtocol'
> note: protocol requires function 'createMyType()' with type '() -> MyType'
> note: candidate has non-matching type '() -> MySubtype'
> 
> I know I can fix it by using associated objects in MyProtocol definition, but then if I want to declare a property of type MyProtocol I have to go dancing with generics everywhere.
> 
> Is this a known limitation/bug? Any plans to improve this?
> 
> Cheers,
> Diego
> 
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20160216/04962a09/attachment.html>


More information about the swift-users mailing list