我正在尝试这种技术: class Pet {}class Dog: Pet {}class House { func getPets() - [Pet] { return [Pet]() }}class DogHouse: House { override func getPets() - [Dog] { return [Dog]() }} DogHouse类以严格满足House getPets的API要求
class Pet {} class Dog: Pet {} class House { func getPets() -> [Pet] { return [Pet]() } } class DogHouse: House { override func getPets() -> [Dog] { return [Dog]() } }
DogHouse类以严格满足House getPets的API要求的方式覆盖House getPets方法.
但是,Swift不理解[Dog] isa [Pet]并且它产生错误Method不会覆盖其超类中的任何方法.
对于子类来说,有什么方法可以使用比其超类更通用的输入或更多限制性输出来实现API?
回答官方提出的问题:是的,Swift在返回类型中允许更多“受限制”的返回类型.此属性正式称为返回类型协方差.考虑这个例子,它是可编译的Swift代码:class Pet {} class Dog: Pet {} class House { func getPets() -> Pet { return Pet() } } class DogHouse: House { override func getPets() -> Dog { return Dog() } }
然而,这里的问题是Array< Dog>与Array< Pet>不是“更受限制”的类型,相反,Array< Pet>不是Array< Dog>的推广.形式上,Array< Dog>不是Array< Pet>的协变量.
为了说明原因,请考虑以下示例:
class House<T> { var occupants = [T]() func addOccupant(_ o: T) { occupants.append(o) } } class Pet {} class Dog: Pet {} class Cat: Pet {} class PetHouseBuilder { func buildHouse() -> House<Pet> { return House() } } class DogHouseBuilder: PetHouseBuilder { // Suppose this were legal override func buildHouse() -> House<Dog> { return House() } } // The concrete return type of the object is `House<Dog>`, but // `PetHouseBuilder.buildHouse` has a static return type of `House<Pet>`, // so `petHouse` will have an inferred static type of `House<Pet>` let petHouse = PetHouseBuilder().buildHouse() let vulnerableLittle