我需要实现一个派生自 UITableViewController
的类(为方便起见,将其命名为 A)和另一个派生自 UICollectionViewController
的类 (B)。而且有很多共同的东西,所以我想把它们放在class(C)中,让A和B继承C。现在A和B都有两个类可以继承,但是swift中不允许多重继承,那怎么办实现这个?我知道 swift 不允许多重继承,但我仍然想知道如何做我上面描述的事情。
最佳答案
如@Paulw11 的评论所述是正确的。这是一个涉及 A 和 B 从 C 继承的示例。我将其命名为 DogViewController
和 CatViewController
(继承自 PetViewController
)。您可以看到协议(protocol)可能有何用处。这只是一个超基本的例子。
protocol Motion {
func move()
}
extension Motion where Self: PetViewController {
func move() {
//Open mouth
}
}
class PetViewController: UIViewController, Motion{
var isLoud: Bool?
func speak(){
//Open Mouth
}
}
class DogViewController:PetViewController {
func bark() {
self.speak()
//Make Bark Sound
}
}
class CatViewController: PetViewController {
func meow() {
self.speak()
//Make Meow Sound
}
}
//....
let cat = CatViewController()
cat.move()
cat.isLoud = false
cat.meow()
关于ios - 如何在swift中进行多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360983/