0
0
Swiftprogramming~10 mins

Associated types in protocols 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 an associated type in the protocol.

Swift
protocol Container {
    associatedtype [1]
}
Drag options to blanks, or click blank then click option'
AElement
BItem
CType
DValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a reserved keyword as the associated type name.
Forgetting to write 'associatedtype' before the name.
2fill in blank
medium

Complete 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'
AItem
BType
CElement
DValue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name than the protocol's associated type.
Omitting 'typealias' keyword.
3fill in blank
hard

Fix 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'
ACodable
BComparable
CHashable
DEquatable
Attempts:
3 left
💡 Hint
Common Mistakes
Using a protocol that does not support equality comparison.
Omitting the constraint entirely.
4fill in blank
hard

Fill 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'
AElement
BItem
CValue
DType
Attempts:
3 left
💡 Hint
Common Mistakes
Using different associated type names for the two containers.
Using a name not declared as an associated type.
5fill in blank
hard

Fill 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'
AElement
BItem
CInt
DValue
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.