Mastering macOS Programming
上QQ阅读APP看书,第一时间看更新

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.