[swift-users] Covariance in Generic Protocols & Proposal 0142

Justin Jia justin.jia.developer at gmail.com
Sun Jun 25 22:46:53 CDT 2017


Hi,

I’m trying to implement something like this using Swift 4 after proposal 0142 is implemented:

```
protocol GenericProtocol {
    associatedtype Instance
    func foo() -> Instance
    func bar() -> Instance
    // and more...
}

protocol A: GenericProtocol where Instance == String { }
protocol B: GenericProtocol where Instance == Int { }
protocol C: GenericProtocol where Instance == Double { }
// and more…

class Bar {
    var a: A // Error: Protocol ‘A' can only be used as a generic constraint because it has Self or associated type requirements
    var b: B // Error: Protocol ‘B' can only be used as a generic constraint because it has Self or associated type requirements
    var c: C // Error: Protocol ‘C' can only be used as a generic constraint because it has Self or associated type requirements
    // and more...
}
```

However, I’m still getting the `Protocol ‘A' can only be used as a generic constraint because it has Self or associated type requirements` error.

Instead, the only thing I can do right now is to duplicate my code:

(Just in case your are wondering, I need this syntax to simplify some code I’m working on https://github.com/TintPoint/Overlay/tree/swift-4.0)

```
protocol A {
    func foo() -> String
    func bar() -> String
    // and more...
}

protocol B {
    func foo() -> Int
    func bar() -> Int
    // and more...
}

protocol B {
    func foo() -> Double
    func bar() -> Double
    // and more...
}

// and more...

class Bar {
    var a: A // OK
    var b: B // OK
    var c: C // OK
    // and more...
}
```

Am I doing something wrong here? Is it Swift’s current limitation that can be improved in a future version of Swift? Or it needs a special syntax and a separate proposal?

Thank you in advance for your help!

Sincerely,
Justin



More information about the swift-users mailing list