ios 如何在swift中进行多继承?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40360983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do multi-inheritance in swift?
提问by Sherwin
I need to implement a class (for convenience name it A) derived from UITableViewController
and another(B) from UICollectionViewController
. And there are a lot of things common, so I want to put them in class(C) and let A and B inherit C. Now A and B both have two class to inherit, but multiple inheritance is not allowed in swift, so how to implement this? I know there is no multi-inheritance allowed in swift, but I still want to know how to do the things I described above.
我需要实现一个UITableViewController
从UICollectionViewController
. 而且有很多共同的东西,所以我想把它们放在class(C)中,让A和B继承C。现在A和B都有两个类要继承,但是swift中不允许多重继承,那么如何实施这个?我知道 swift 中不允许多继承,但我仍然想知道如何做我上面描述的事情。
回答by Asdrubal
As stated in the comments by @Paulw11 is correct. Here is an example that involves A& Binheriting from C. Which I have named DogViewController
and CatViewController
(which inherits form PetViewController
). You can see how a protocol might be useful. This is just an ultra basic example.
正如@Paulw11 在评论中所述是正确的。这是一个涉及A& B从C继承的示例。我已经命名DogViewController
和CatViewController
(它继承了 form PetViewController
)。您可以看到协议如何有用。这只是一个超基本的例子。
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()
回答by jalone
回答by Onur Tuna
Multiple inheritance is not allowed in Swift. You can conform any protocol instead. Protocols are like interfaces in Java.
Swift 中不允许多重继承。您可以改为遵守任何协议。协议就像 Java 中的接口。