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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:41:22  来源:igfitidea点击:

How to do multi-inheritance in swift?

iosswift

提问by Sherwin

I need to implement a class (for convenience name it A) derived from UITableViewControllerand 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.

我需要实现一个UITableViewControllerUICollectionViewController. 而且有很多共同的东西,所以我想把它们放在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 DogViewControllerand CatViewController(which inherits form PetViewController). You can see how a protocol might be useful. This is just an ultra basic example.

正如@Paulw11 在评论中所述是正确的。这是一个涉及A& BC继承的示例。我已经命名DogViewControllerCatViewController(它继承了 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

You can't have multiple inheritance in Swift, the way to go is to look at Protocols, but it is a rather big topic to be discussed in an answer.

在 Swift 中你不能有多重继承,要走的路是看协议,但这是一个相当大的话题,需要在答案中讨论。

There are also many other questionswith the same scope

还有许多其他问题具有相同的范围

回答by Onur Tuna

Multiple inheritance is not allowed in Swift. You can conform any protocol instead. Protocols are like interfaces in Java.

Swift 中不允许多重继承。您可以改为遵守任何协议。协议就像 Java 中的接口。