Updated 4 March 2022
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. Learn more about inheritance from here.
As we have two classes with the same function and the third class which don’t know about the functions which are common in them.
Please check the example below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class First { func doRunning() { print("Do Running from First") } } class Second { func doRunning() { print("Do Running from Second") } } class MyClass: First, Second { } |
In other words, this will give an error as multiple inheritances are not supported by Swift.
We can achieve the multiple in Swift using the protocols.
Protocols are the set of methods and variables, which can be extended by class and use its function and variables. Therefore, we can use protocols for extending functions and variables.
Please follow the below steps for integration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
protocol First { var height: Int {get set} } protocol Second { var width: Int {get set} } class MyClass: First, Second { var height: Int = 80 var width: Int = 40 func getAreaOfSquare() -> Int { return height * width } } var objc = MyClass() objc.getAreaOfSquare() |
In the above code, we have used two protocols and simply inherit them in the class. Similarly, we can also use the same architecture. And inherent the class into the protocols and then inherited the protocols into the main class.
In addition, we can also use the third way by inheriting one class into another class and another class to the main class in Swift.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class First { func doRunning() { print("Do Running from First") } } class Second: First { func doWork() { print("Do Work from Second") } } class MyClass: Second { } var objc = MyClass() objc.doWork() |
In Conclusion
We have successfully integrated the multiple inheritances in Swift using protocols. If you have any issues or suggestions you can leave your message in the comment section Please check out my other blogs from here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.