0
0
Swiftprogramming~5 mins

Protocol composition in practice in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AProtocolA + ProtocolB
BProtocolA | ProtocolB
CProtocolA, ProtocolB
DProtocolA & ProtocolB
What does a function parameter typed as Readable & Writable require?
AAn object that is both Readable and Writable
BAn object that is only Readable
CAn object that is neither Readable nor Writable
DAn object that is either Readable or Writable
Can protocol composition be used with structs in Swift?
ANo, only classes can use protocol composition
BOnly enums can use protocol composition
CYes, any type can conform to multiple protocols
DOnly protocols can use protocol composition
What is a benefit of using protocol composition?
AIt allows combining multiple behaviors flexibly
BIt forces inheritance from a single class
CIt restricts types to only one protocol
DIt replaces all protocols with classes
If a protocol is class-only, what happens when you compose it with another protocol?
AThe composition is no longer class-only
BThe composition remains class-only
CThe composition becomes a struct
DThe composition is invalid
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.