Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can not inherit from multiple classes in swift just like it's library classes

Tags:

swift

I try to create myPet by inherit from two classes but error for example:

import UIKit class SecondViewController: UIViewController, UITextFieldDelegate {     // No Error } 

Then the following classes were defined then create new class myPets which I like to inherit both Dog and Substance. But error: Multiple inheritance from classes 'Dog' and 'Substance'

class Dog:Animal {     func sound()->String {         return "Hong Hong"     } }  class Substance {     func livingCompound()->String {         return "Consist of bio-molecule"     } }  class myPets:Dog, Substance {     func itsAddress()->String {         // Error:Multiple inheritance from classes 'Dog' and 'Substance'     } } 
like image 344
PKul Avatar asked Aug 31 '14 19:08

PKul


People also ask

Why multiple inheritance is not possible in Swift?

Swift doesn't allow us to declare a class with multiple base classes or superclasses, so there is no support for multiple inheritance of classes. A subclass can inherit just from one class. However, a class can conform to one or more protocols.

Can a class inherit from multiple classes Swift?

Swift does not support multiple inheritance. That is, you cannot inherit from more than one class.

Why we Cannot inherit multiple classes?

The reason behind this is to prevent ambiguity. Consider a case where class B extends class A and Class C and both class A and C have the same method display(). Now java compiler cannot decide, which display method it should inherit. To prevent such situation, multiple inheritances is not allowed in java.

Is it possible to inherit from multiple classes at the same time?

If a class inherits, it has the methods and variables from the parent classes. In essence, it's called multiple inheritance because a class can inherit from multiple classes. This is a concept from object orientated programming.


1 Answers

Swift does not support multiple inheritance, following Objective C in this. This is NOT inheritance from two classes:

class SecondViewController: UIViewController, UITextFieldDelegate 

It is inheritance from one class UIViewController and adopting the UITextFieldDelegate protocol. Read about protocols at https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

like image 156
Wojtek Surowka Avatar answered Sep 29 '22 12:09

Wojtek Surowka