Recall & Review
beginner
What is protocol composition in Swift?
Protocol composition lets you combine multiple protocols into one requirement, so a type must conform to all of them at once.
Click to reveal answer
beginner
How do you write a protocol composition type in Swift?
Use the syntax:
ProtocolA & ProtocolB to require a type that conforms to both ProtocolA and ProtocolB.Click to reveal answer
intermediate
Why use protocol composition instead of inheritance?
Protocol composition allows combining behaviors from multiple protocols without needing a class hierarchy, making code more flexible and reusable.Click to reveal answer
beginner
Example: What does this mean? <br>
func performAction(on object: Drawable & Animatable)The function requires an object that conforms to both Drawable and Animatable protocols, so it can draw and animate the object.
Click to reveal answer
intermediate
Can protocol composition be used with class-only protocols?
Yes, you can combine class-only protocols using protocol composition, and the resulting type will also be class-constrained.
Click to reveal answer
Which syntax correctly represents protocol composition in Swift?
✗ Incorrect
Protocol composition uses the & symbol to combine protocols.
What does a function parameter typed as
Readable & Writable require?✗ Incorrect
The & means the object must conform to both protocols.
Can protocol composition be used with structs in Swift?
✗ Incorrect
Structs can conform to multiple protocols and be used with protocol composition.
What is a benefit of using protocol composition?
✗ Incorrect
Protocol composition lets you combine multiple protocols for flexible design.
If a protocol is class-only, what happens when you compose it with another protocol?
✗ Incorrect
Class-only constraints carry over in protocol composition.
Explain how protocol composition works in Swift and give a simple example.
Think about how you can require multiple behaviors at once.
You got /3 concepts.
Describe a real-life scenario where protocol composition would be useful in Swift programming.
Imagine an object that needs to do more than one thing.
You got /3 concepts.