[swift-users] Covariance in protocol adoption

Diego Sánchez diego.sanchezr at gmail.com
Tue Feb 16 13:47:54 CST 2016

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?

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

More information about the swift-users mailing list