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?

倾然丶 夕夏残阳落幕 提交于 2019-12-19 03:42:10

问题


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 to define this function, but with a SubclassType return type.

Compiler tells me, that this class does not conform to the protocol, 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, though, that SubclassType should be a suitable substitute for a SuperclassType in this matter.

What am I doing wrong?

Thanks.


回答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 {
    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 adopting SomeProtocol must be either SuperclassType or a subtype thereof.



来源:https://stackoverflow.com/questions/35094967/swift-how-can-i-make-a-function-with-a-subclass-return-type-conform-to-a-protoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!