如何在swift中进行多重继承?

She*_*win 8 ios swift

我需要实现一个派生的类(为了便利名称A)UITableViewController和另一个派生的(B)UICollectionViewController.并且有很多常见的东西,所以我想把它们放在类(C)中让A和B继承C.现在A和B都有两个继承类,但是swift中不允许多重继承,所以如何实现这个?我知道swift中不允许多重继承,但我仍然想知道如何做我上面描述的事情.

Asd*_*bal 19

正如@ Paulw11的评论所述,是正确的.这是一个涉及从C继承的A&B的例子.我已经命名和(继承形式).您可以看到协议如何有用.这只是一个非常基本的例子.DogViewControllerCatViewControllerPetViewController

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()
Run Code Online (Sandbox Code Playgroud)


jal*_*one 5

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

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


Onu*_*una 5

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