0
0
Swiftprogramming~5 mins

Protocol composition 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. 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?
AProtocolA & ProtocolB
BProtocolA | ProtocolB
CProtocolA + ProtocolB
DProtocolA, ProtocolB
What does a function parameter typed as ProtocolA & ProtocolB require?
AAn object conforming to ProtocolA only
BAn object conforming to either ProtocolA or ProtocolB
CAn object conforming to both ProtocolA and ProtocolB
DAn object conforming to ProtocolB only
Can protocol composition include class type constraints?
AYes, by including AnyObject in the composition
BNo, only protocols can be composed
CYes, by using class keyword inside composition
DNo, class types are separate
Why might you use protocol composition instead of defining a new protocol?
ATo inherit from multiple classes
BTo create a new class
CTo override protocol methods
DTo avoid code duplication and combine existing protocols
Which of these is NOT a valid protocol composition in Swift?
AProtocolA & AnyObject
BProtocolA | ProtocolB
CProtocolA & ProtocolB
DProtocolA & ProtocolB & AnyObject
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.