- Mastering macOS Programming
- Stuart Grimshaw
- 116字
- 2021-07-02 22:54:37
Protocol composition
We can declare types to conform to more than one protocol, creating a type that satisfies the requirements of both protocols. This is called protocol composition.
Let's first declare another protocol:
protocol Pensive
{
func reactToStimulus()
}
Now we can declare a type that conforms to both the Talkative and Pensive protocols:
struct Philosopher: Talkative, Pensive
{
func sayHi()
{
print("hi")
}
func reactToStimulus()
{
print("I thing therefore I am")
}
}
The syntax of declaring protocol compliance looks much like the syntax for declaring subclasses, but value types cannot inherit from other types (that is, declare themselves as subclasses). However, adopting a protocol is to all intents and purposes a form of inheritance.