Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a protocol with an associated type named Item.
Swift
protocol Container {
associatedtype [1]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a keyword like 'Type' which is reserved in Swift.
Choosing a name that is not descriptive or conventional.
✗ Incorrect
The keyword
associatedtype is followed by the name of the associated type, which in this case is Item.2fill in blank
mediumComplete the code to declare a function in the protocol that returns an element of the associated type.
Swift
protocol Container {
associatedtype Item
func getItem() -> [1]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Any' which is too general.
Using 'Void' which means no return value.
✗ Incorrect
The function returns the associated type
Item, so the return type must be Item.3fill in blank
hardFix the error in the struct declaration that conforms to the protocol with an associated type.
Swift
struct Box: Container {
typealias [1] = String
func getItem() -> String {
return "Hello"
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name like 'Element' which does not match the protocol.
Omitting the typealias entirely.
✗ Incorrect
The protocol's associated type is named 'Item', so the typealias must match that name exactly.
4fill in blank
hardFill both blanks to complete the generic function that accepts any Container and returns its item.
Swift
func fetchItem<C: Container>(from container: C) -> [1] { return container.[2]() }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using just 'Item' as return type without prefixing with generic parameter.
Calling a method name that does not exist like 'fetch()'.
✗ Incorrect
The return type is the associated type of the generic parameter, written as 'C.Item'. The function to get the item is 'getItem()'.
5fill in blank
hardFill all three blanks to define a protocol with an associated type and a property of that type.
Swift
protocol Storage {
associatedtype [1]
var [2]: [3] { get set }
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the associated type and property type.
Using property names that do not match the code style.
✗ Incorrect
The associated type is named 'DataType'. The property name is 'data' and its type is 'DataType'.