Recall & Review
beginner
What is protocol composition in Swift?
Protocol composition lets you combine multiple protocols into one requirement. It means a type must conform to all listed protocols.
Click to reveal answer
beginner
How do you write a protocol composition type in Swift?
Use the ampersand (&) symbol between protocols, like
ProtocolA & ProtocolB.Click to reveal answer
intermediate
Why use protocol composition instead of a single protocol?
It allows flexibility by combining existing protocols without creating a new one. You can require multiple behaviors at once.
Click to reveal answer
beginner
Example: What does this mean?<br>
func performAction(with object: ProtocolA & ProtocolB)The function accepts an object that conforms to both ProtocolA and ProtocolB. The object must implement all requirements from both.
Click to reveal answer
intermediate
Can protocol composition be used with class and protocol types?Yes. You can combine protocols and also require a class type by adding <code>AnyObject</code> in the composition, like <code>ProtocolA & AnyObject</code>.Click to reveal answer
How do you combine two protocols, ProtocolA and ProtocolB, in Swift?
✗ Incorrect
Use the ampersand (&) to combine protocols in Swift.
What does a function parameter typed as
ProtocolA & ProtocolB require?✗ Incorrect
The object must conform to all protocols in the composition.
Can protocol composition include class type constraints?
✗ Incorrect
Including AnyObject restricts the composition to class types.
Why might you use protocol composition instead of defining a new protocol?
✗ Incorrect
Protocol composition combines existing protocols without creating a new one.
Which of these is NOT a valid protocol composition in Swift?
✗ Incorrect
The | symbol is not used for protocol composition in Swift.
Explain what protocol composition is and how it is used in Swift.
Think about how you can require multiple behaviors at once.
You got /3 concepts.
Describe a situation where protocol composition is better than creating a new protocol.
Consider when you want to require multiple capabilities without new names.
You got /3 concepts.