Swift: How can I create a function with a protocol-compatible return subclass type where Superclass is defined as a return type?

I have a protocol in which a function is defined, the return type of the function is SuperclassType .

In a class that conforms to the protocol, I am trying to define this function, but with a return type of SubclassType .

The compiler tells me that this class is not protocol compliant, because obviously SubclassType ! = SuperclassType

 protocol SomeProtocol { func someFunction(someParameter:SomeType) -> SuperclassType? } class SomeClass : SomeProtocol { func someFunction(someParameter:SomeType) -> SubclassType? { ... } } class SubclassType : SuperclassType { } 

Common sense tells me that SubclassType should be a suitable replacement for SuperclassType in this matter.

What am I doing wrong?

Thanks.

+2
source share
1 answer

Before you go any further, I would recommend some background readings of covariance versus contravariance and the Liskov Substitution Principle .

  • Return types for overridden methods when subclasses are covariant : overriding a subclass of a method can return a subtype of the return type of a superclass method.

  • Parameters of a type type are invariant : specialization can neither narrow nor extend the requirements for a type.

The relationship between the protocol and the specific type that uses it is more like generators than subclasses, so return types declared in protocols are also invariant. (It is difficult to say exactly why on first reading. Perhaps something about existential and only for limitations only for limitations?)

You can enable covariance in the protocol by specifying related type requirements:

 protocol SomeProtocol { typealias 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 that accepts SomeProtocol must be either SuperclassType or its subtype.

+6
source

All Articles