Created
February 17, 2016 12:54
-
-
Save diegosanchezr/5a66c7af862e1117b556 to your computer and use it in GitHub Desktop.
Protocol covariance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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' |
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
XCode 7.2.1