Swift没有抽象的类和方法.相反,它提供协议.
当你的课程完全抽象或完全具体时,这很好.
但是,实现具有具体方法的抽象类的最佳“Swift”方法是什么?
伪代码示例:
- class Animal {
- abstract makeSound()
- abstract eyeCount()
- }
- class Mammal : Animal {
- override eyeCount { return 2 } // Let's assume all mammals have hard-coded 2 eyes...
- class Cat : Mammal {
- override makeSound { print "Meow!" }
- }
- class Dog : Mammal {
- override makeSound { print "Woof!" }
- }
在哺乳动物中,我确实想要实施具体的方法eyeCount(),因为所有的哺乳动物都有2个硬编码的眼睛(据说是),我不想在狗和猫中重新实现它.但是,makeSound()只能用于Dog和Cat,因为哺乳动物的声音各不相同.
你会如何在Swift中实现它?谢谢!
解决方法
我会像这样实现它:
- class AbstractAnimal
- {
- // Fully abstract method
- func methodThatReturnsSomething() -> String {
- fatalError("methodThatReturnsSomething() is abstract and must be overriden!");
- }
- func eyeCount() -> Int {
- return 2;
- }
- }
fatalError阻止Xcode抱怨抽象方法methodThatReturnsSomething()实际上没有返回任何东西.