I have a protocol, where a function is defined, the return type of a function is a SuperclassType
.
In a class which conforms to the protocol I\'m trying
Before you go much further, I'd recommend some background reading on covariance vs contravariance and the Liskov substitution principle.
Return types for methods overridden when subclassing are covariant: the subclass override of a method can return a subtype of the superclass method's return type.
Generic type parameters are invariant: a specialization can neither narrow nor expand the type requirements.
The relationship between a protocol and a concrete type that adopts it is more like generics than like subclassing, so return types declared in protocols are invariant, too. (It's hard to say exactly why on first read. Possibly something about existential vs constraint-only protocols?)
You can allow covariance in a protocol by specifying associated type requirements, though:
protocol SomeProtocol {
associatedtype ReturnType: SuperclassType
func someFunction(someParameter: SomeType) -> ReturnType
}
class SomeClass : SomeProtocol {
func someFunction(someParameter: SomeType) -> SubclassType { /*...*/ }
}
Now, it's clear that the return type of someFunction
in a type adopting SomeProtocol
must be either SuperclassType
or a subtype thereof.