Recall & Review
beginner
What is a protocol extension in Swift?
A protocol extension in Swift allows you to add methods, properties, and default implementations to a protocol. This means any type that adopts the protocol can use these default behaviors without having to implement them explicitly.
Click to reveal answer
beginner
How do default implementations in protocol extensions help reduce code duplication?
Default implementations provide a shared behavior for all types conforming to the protocol. Instead of writing the same method in every conforming type, you write it once in the protocol extension, and all conforming types get it automatically.
Click to reveal answer
intermediate
Can a conforming type override a default implementation provided by a protocol extension?
Yes, a conforming type can provide its own implementation of a method or property, which will override the default implementation from the protocol extension.
Click to reveal answer
intermediate
What happens if a method is declared in a protocol and also implemented in its extension, but a conforming type provides its own implementation?
The conforming type's implementation is used instead of the default one from the protocol extension. This allows customization while still benefiting from default behavior when no custom implementation is provided.
Click to reveal answer
intermediate
Why can't protocol extensions add stored properties?
Protocol extensions can only add computed properties or methods because protocols don't have storage. Stored properties require memory allocation, which is only possible in concrete types, not protocols.
Click to reveal answer
What is the main benefit of using default implementations in protocol extensions?
✗ Incorrect
Default implementations allow shared behavior so conforming types don't have to write the same code repeatedly.
Can a conforming type override a method provided by a protocol extension?
✗ Incorrect
Conforming types can always override default implementations with their own versions.
Which of the following can NOT be added in a protocol extension?
✗ Incorrect
Protocol extensions cannot add stored properties because protocols don't have storage.
If a protocol declares a method and its extension provides a default implementation, what happens if a conforming type does NOT implement that method?
✗ Incorrect
The conforming type uses the default implementation from the protocol extension.
Why are protocol extensions useful in Swift?
✗ Incorrect
Protocol extensions provide default behavior and help avoid repeating code in multiple types.
Explain how protocol extensions with default implementations work in Swift and why they are useful.
Think about how you can write one method once and use it in many types.
You got /4 concepts.
Describe the limitations of protocol extensions regarding stored properties and how you can work around them.
Remember protocols don't have memory to store data.
You got /4 concepts.