Files
swift-mirror/userdocs/diagnostics/multiple-inheritance.md
Jevon Mao 9397ee59d5 [Diagnostics] Add educational notes explaining multiple inheritance (#38253)
* Add educational notes for multiple inheritance

* Update edu note by adopting reviewer suggestions

* Update userdocs/diagnostics/multiple-class-inheritance.md

Co-authored-by: Varun Gandhi <varun_gandhi@apple.com>

* Added Flyable protocol definition to example

* Apply suggestions from code review

Co-authored-by: Varun Gandhi <varun_gandhi@apple.com>

* Apply suggestions from code review

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

* Use consistent terminology

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

* Use utensils example as suggested by review

* Update title to Multiple Inheritance

* Apply suggestions from code review

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

* Rename file to match changed name

* Add more objects in protocol construction example

* Apply suggestions from code review

Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>

Co-authored-by: Varun Gandhi <varun_gandhi@apple.com>
Co-authored-by: Xiaodi Wu <13952+xwu@users.noreply.github.com>
2021-08-01 08:06:38 -04:00

1.7 KiB

Multiple Inheritance

In some programming languages, a class can inherit the interface of multiple base classes. Known as multiple inheritance, this feature can add significant complexity to the language and is unsupported in Swift. Instead, Swift allows composition of interfaces using protocols.

Consider the following example:

protocol Utensil { 
    var name: String { get }
} 

protocol ServingUtensil: Utensil {
    func serve()
} 

extension ServingUtensil {
    func serve() { /* Default implementation. */ }
}

protocol Fork: Utensil {
    func spear()
}

protocol Spoon: Utensil {
    func scoop()
}

struct CarvingFork: ServingUtensil, Fork { /* ... */ }
struct Spork: Spoon, Fork { /* ... */ }
struct Ladle: ServingUtensil, Spoon { /* ... */ }

Swift protocols can declare interfaces that must be implemented by each conforming type (like abstract class members in other programming languages such as C# or Java), and they can also provide overridable default implementations for those requirements in protocol extensions.

When class inheritance and protocol conformances are used together, subclasses inherit protocol conformances from base classes, introducing additional complexity. For example, the default implementation of a protocol requirement not overridden in the conforming base class also cannot be overridden in any subclass (SR-103).

To learn more about defining and adopting protocols, see the Protocols section in The Swift Programming Language. To learn more about class inheritance, see the Inheritance section in The Swift Programming Language.