Recall & Review
beginner
What is a protocol with associated types in Swift?
A protocol with associated types defines a placeholder type that is used as part of the protocol. It lets the protocol work with types that are not specified until the protocol is adopted.
Click to reveal answer
beginner
How do you declare an associated type in a Swift protocol?
Use the keyword
associatedtype followed by the name of the placeholder type inside the protocol definition.Click to reveal answer
beginner
Why use associated types in protocols?
They allow protocols to be flexible and work with different types without specifying exact types upfront, making code more reusable and generic.
Click to reveal answer
intermediate
What happens if a protocol with an associated type is used as a type directly?
You cannot use a protocol with associated types as a concrete type directly because the associated type is not specified. You must use generics or type erasure.
Click to reveal answer
beginner
Show a simple example of a protocol with an associated type and a struct that adopts it.
Example:<br>
protocol Container {
associatedtype Item
mutating func add(_ item: Item)
}
struct Box: Container {
var items = [String]()
mutating func add(_ item: String) {
items.append(item)
}
}Click to reveal answer
What keyword declares an associated type in a Swift protocol?
✗ Incorrect
The keyword
associatedtype is used to declare a placeholder type inside a protocol.Can you use a protocol with associated types as a concrete type directly?
✗ Incorrect
No, you cannot use a protocol with associated types as a concrete type directly because the associated type is not specified. You must use generics or type erasure.
What is the main benefit of using associated types in protocols?
✗ Incorrect
Associated types let protocols work with different types, making code flexible and reusable.
Which of these is a valid associated type declaration?
✗ Incorrect
The correct syntax is
associatedtype Item inside a protocol.If a protocol has an associated type, how do you usually use it?
✗ Incorrect
You use generics constrained to the protocol to specify the associated type.
Explain what a protocol with associated types is and why it is useful in Swift.
Think about how protocols can work with different types without fixing them.
You got /4 concepts.
Describe how you would implement a protocol with an associated type and use it in a struct.
Show a simple example with a container and an item type.
You got /4 concepts.