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

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

解决方法

正如@ Paulw11的评论所述,是正确的.这是一个涉及A& A的例子. B继承自C.我将其命名为DogViewController和CatViewController(继承了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()

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...