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.
The only way to implement multiple inheritance is to implement multiple interfaces in a class. In java, one class can implements two or more interfaces. This also does not cause any ambiguity because all methods declared in interfaces are implemented in class.
In this blog, we are going to learn about the multiple inheritances in Swift and their implementation in your iOS project. Swift is an Object-oriented programming language but it does not support multiple inheritances.
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass.
Yes in Swift and Objective-c Single and Multilevel inheritance is supported. In swift and many other languages Multiple Inheritance is restricted by use of classes because of historical problems like deadly diamond and others ambiguities.In swift you can achieve the Multiple inheritance at some level by Protocols .
As stated in the comments by @Paulw11 is correct. Here is an example that involves A & B inheriting 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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With