Challenge - 5 Problems
Swift Type Erasure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of type-erased wrapper usage
What is the output of this Swift code using type erasure with AnySequence?
Swift
struct IntSequence: Sequence { func makeIterator() -> some IteratorProtocol { return (1...3).makeIterator() } } let seq: AnySequence<Int> = AnySequence(IntSequence()) for num in seq { print(num, terminator: " ") }
Attempts:
2 left
💡 Hint
Think about how AnySequence hides the underlying sequence type but still iterates correctly.
✗ Incorrect
AnySequence erases the concrete type IntSequence but preserves iteration behavior, so it prints 1 2 3.
🧠 Conceptual
intermediate1:30remaining
Purpose of type erasure in Swift
Why do Swift developers use type erasure?
Attempts:
2 left
💡 Hint
Think about how protocols with associated types limit usage.
✗ Incorrect
Type erasure hides the concrete underlying type and exposes a uniform interface, allowing use of protocols with associated types or self requirements.
🔧 Debug
advanced2:30remaining
Fix the error in this type erasure example
What error does this code produce and why?
protocol Shape {
associatedtype Color
func draw() -> Color
}
struct AnyShape: Shape {
private let _draw: () -> C
init(_ shape: S) where S.Color == C {
_draw = shape.draw
}
func draw() -> C {
_draw()
}
}
struct Circle: Shape {
func draw() -> String { "Circle" }
}
let shape = AnyShape(Circle())
Attempts:
2 left
💡 Hint
Check the associatedtype requirements in the protocol and the struct.
✗ Incorrect
Circle does not specify the associated type 'Color' required by Shape, so it does not conform. This causes a compile error.
📝 Syntax
advanced1:00remaining
Identify the syntax error in this type erasure wrapper
Which option correctly fixes the syntax error in this Swift type erasure code?
struct AnyWrapper {
private let _value: T
init(_ value: T) {
_value = value
}
func getValue() -> T {
return _value
}
}
let wrapper = AnyWrapper(5)
print(wrapper.getValue()
Attempts:
2 left
💡 Hint
Check the parentheses balance in the print statement.
✗ Incorrect
The print statement is missing a closing parenthesis, causing a syntax error. Adding it fixes the code.
🚀 Application
expert3:00remaining
How many elements does this type-erased sequence contain?
Consider this Swift code using type erasure. How many elements will be printed?
struct EvenNumbers: Sequence {
func makeIterator() -> some IteratorProtocol {
(2...10).filter { $0 % 2 == 0 }.makeIterator()
}
}
let numbers = AnySequence(EvenNumbers())
var count = 0
for _ in numbers {
count += 1
}
print(count)
Attempts:
2 left
💡 Hint
Count even numbers between 2 and 10 inclusive.
✗ Incorrect
Even numbers between 2 and 10 inclusive are 2,4,6,8,10, totaling 5 elements.