Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare an associated type in the protocol.
Swift
protocol Container {
associatedtype [1]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a reserved keyword as the associated type name.
Forgetting to write 'associatedtype' before the name.
✗ Incorrect
The keyword 'associatedtype' is followed by the name of the associated type, commonly 'Element'.
2fill in blank
mediumComplete the code to specify the associated type in a struct conforming to the protocol.
Swift
struct Stack: Container {
typealias [1] = Int
var items = [Int]()
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name than the protocol's associated type.
Omitting 'typealias' keyword.
✗ Incorrect
To specify the associated type, use 'typealias' followed by the associated type name, which is 'Element'.
3fill in blank
hardFix the error in the protocol declaration by completing the associated type constraint.
Swift
protocol Container {
associatedtype Element: [1]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a protocol that does not support equality comparison.
Omitting the constraint entirely.
✗ Incorrect
The associated type 'Element' is constrained to conform to 'Equatable' to allow equality checks.
4fill in blank
hardFill both blanks to complete the generic function using the protocol with associated type.
Swift
func allItemsMatch<C1: Container, C2: Container>(_ someContainer: C1, _ anotherContainer: C2) -> Bool where C1.[1] == C2.[2] { // function body return false }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different associated type names for the two containers.
Using a name not declared as an associated type.
✗ Incorrect
Both containers must have the same associated type 'Element' to compare their items.
5fill in blank
hardFill all three blanks to complete the protocol and conforming struct with associated type and method.
Swift
protocol Container {
associatedtype [1]
mutating func append(_ item: [2])
var count: Int { get }
subscript(i: Int) -> [3] { get }
}
struct IntStack: Container {
var items = [Int]()
mutating func append(_ item: Int) {
items.append(item)
}
var count: Int {
items.count
}
subscript(i: Int) -> Int {
items[i]
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent type names between protocol and struct.
Not matching the associated type with method parameters and return types.
✗ Incorrect
The protocol declares an associated type 'Element', and the methods use 'Element' which is 'Int' in the conforming struct.