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

标签 ios swift

我需要实现一个派生自 UITableViewController 的类(为方便起见,将其命名为 A)和另一个派生自 UICollectionViewController 的类 (B)。而且有很多共同的东西,所以我想把它们放在class(C)中,让A和B继承C。现在A和B都有两个类可以继承,但是swift中不允许多重继承,那怎么办实现这个?我知道 swift 不允许多重继承,但我仍然想知道如何做我上面描述的事情。

最佳答案

如@Paulw11 的评论所述是正确的。这是一个涉及 ABC 继承的示例。我将其命名为 DogViewControllerCatViewController(继承自 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/

相关文章:

ios - 在 Firebase 数据库中创建节点后如何阻止访问更改?

ios - 选择时更改 UITableViewCell 的 alpha 不执行任何操作

ios - 在 Xcode 5 中,即使 SDK 目录中有 iOS SDK 6.1,如何使用 iOS SDK 7.0 进行构建?

ios - iOS 13 中的自动旋转错误

ios - 标签约束不起作用

ios - 我是否必须在 ARC 下调用 dispatch_release?

swift - cocoa应用程序中关于串口获取操作不允许的Xcode C++代码

ios - 将数据从 uitableview 传递到其他 uiview

ios - `NSDictionary` 不能隐式转换为 `[NSObject : AnyObject]`

swift - 我什么时候应该使用deinit?