0
0
Swiftprogramming~10 mins

Protocol with associated types in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AType
BElement
CItem
DContent
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.
2fill in blank
medium

Complete 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'
AItem
BSelf
CAny
DVoid
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'Any' which is too general.
Using 'Void' which means no return value.
3fill in blank
hard

Fix 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'
AValue
BElement
CContent
DItem
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name like 'Element' which does not match the protocol.
Omitting the typealias entirely.
4fill in blank
hard

Fill 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'
AC.Item
BgetItem
CItem
Dfetch
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()'.
5fill in blank
hard

Fill 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'
ADataType
Bdata
Dcontent
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.