Skip to content

Instantly share code, notes, and snippets.

@diegosanchezr
Created February 17, 2016 12:54
Show Gist options
  • Save diegosanchezr/5a66c7af862e1117b556 to your computer and use it in GitHub Desktop.
Save diegosanchezr/5a66c7af862e1117b556 to your computer and use it in GitHub Desktop.
Protocol covariance
// 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'
@ftp27
Copy link

ftp27 commented Jun 27, 2017

protocol MyProtocol {
    associatedtype SomeType
    func createMyType() -> SomeType
}

class MyConformingClass: MyProtocol {
    typealias SomeType = MySubtype
    func createMyType() -> MySubtype {
        return MySubtype()
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment