Swift: How can I make a function with a Subclass return type conform to a protocol, where a Superclass is defined as a return type?

前端 未结 1 1505
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 19:28

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

相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题