0
0
Swiftprogramming~10 mins

Type erasure concept 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.

Swift
protocol Container {
    associatedtype Item
    func add(_ item: [1])
}
Drag options to blanks, or click blank then click option'
AInt
BItem
CAny
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a concrete type like Int or String instead of the associatedtype.
Using Any which loses type information.
2fill in blank
medium

Complete the code to define a type-erased wrapper class for the Container protocol.

Swift
class AnyContainer<T>: Container {
    private let _add: (T) -> Void

    init<C: Container>(_ container: C) where C.Item == T {
        _add = container.add
    }

    func add(_ item: [1]) {
        _add(item)
    }
}
Drag options to blanks, or click blank then click option'
AT
BItem
CContainer
DAny
Attempts:
3 left
💡 Hint
Common Mistakes
Using Any loses type safety.
Using Container or Item as parameter types is incorrect here.
3fill in blank
hard

Fix the error in the type-erased wrapper initializer to correctly capture the add method.

Swift
init<C: Container>(_ container: C) where C.Item == T {
    _add = container.[1]
}
Drag options to blanks, or click blank then click option'
Aadd(item:)
Badd
Cadd()
Dadd(_:)
Attempts:
3 left
💡 Hint
Common Mistakes
Using add() calls the method instead of referencing it.
Using add without parameter label causes errors.
4fill in blank
hard

Fill both blanks to complete a type-erased container that stores elements and erases type.

Swift
class AnyContainer<T>: Container {
    private var items: [T] = []
    private let _add: (T) -> Void

    init<C: Container>(_ container: C) where C.Item == T {
        _add = container.[1]
    }

    func add(_ item: [2]) {
        items.append(item)
        _add(item)
    }
}
Drag options to blanks, or click blank then click option'
Aadd(_:)
Badd()
CT
DAny
Attempts:
3 left
💡 Hint
Common Mistakes
Using add() calls the method instead of referencing it.
Using Any as parameter type loses type safety.
5fill in blank
hard

Fill all three blanks to create a type-erased container that forwards add calls and stores items.

Swift
class AnyContainer<T>: Container {
    private var items: [[1]] = []
    private let _add: (T) -> Void

    init<C: Container>(_ container: C) where C.Item == [2] {
        _add = container.[3]
    }

    func add(_ item: T) {
        items.append(item)
        _add(item)
    }
}
Drag options to blanks, or click blank then click option'
AT
BItem
Cadd(_:)
DAny
Attempts:
3 left
💡 Hint
Common Mistakes
Using Item instead of T in the array or constraint.
Using Any loses type safety.
Using add() calls the method instead of referencing it.