Swift 没有抽象类和方法。相反,它提供协议(protocol)。
当您的类完全抽象或完全具体时,这很好。
但是,实现具有具体方法的抽象类的最佳“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!" }
}
在 Mammal 中,我确实想实现具体方法 eyeCount()
,因为所有哺乳动物都有 2 只硬编码的眼睛(据推测),我不想在 dog 和猫。但是,makeSound()
应该只为狗和猫实现,因为哺乳动物有不同的声音。
您将如何在 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()
实际上没有返回任何东西。
关于ios - Swift - 混合抽象和具体方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30574478/