Type erasure is a technique to hide specific type information behind a common interface, allowing different types to be treated uniformly without exposing their concrete types.
Click to reveal answer
beginner
Why do we use type erasure in Swift?
We use type erasure to work around limitations of protocols with associated types or self requirements, enabling us to store or pass around heterogeneous types that conform to the same protocol.
Click to reveal answer
intermediate
How does a AnySequence in Swift demonstrate type erasure?
AnySequence hides the concrete sequence type and exposes a uniform interface, so you can use different sequence types interchangeably without knowing their exact types.
Click to reveal answer
intermediate
What is a common pattern to implement type erasure in Swift?
Create a wrapper struct or class that conforms to the protocol and holds a private instance of the concrete type. The wrapper forwards calls to the underlying instance, hiding its type.
Click to reveal answer
beginner
Give a simple example of type erasure in Swift.
A wrapper like AnyHashable erases the type of any hashable value, allowing you to store different hashable types in a single collection.
Click to reveal answer
What problem does type erasure solve in Swift?
AAllows hiding concrete types behind a common interface
BImproves runtime performance by avoiding type checks
CAutomatically converts types to strings
DPrevents memory leaks in closures
✗ Incorrect
Type erasure hides concrete types so different types can be used uniformly through a common interface.
Which Swift feature often requires type erasure to be used?
AProtocols with associated types
BClasses with inheritance
CGlobal functions
DStored properties
✗ Incorrect
Protocols with associated types cannot be used as types directly, so type erasure helps to work around this.
What does AnySequence do in Swift?
ASorts sequences alphabetically
BCreates a new sequence type
CErases the type of any sequence
DConverts sequences to arrays
✗ Incorrect
AnySequence erases the concrete sequence type, allowing different sequences to be used interchangeably.
How is type erasure typically implemented?
ABy subclassing all types
BUsing a wrapper that forwards calls to the underlying type
CBy using global variables
DBy converting types to strings
✗ Incorrect
A wrapper struct or class forwards protocol calls to the hidden concrete type, implementing type erasure.
Which of these is an example of a type-erased wrapper in Swift?
AInt
BArray
CString
DAnyHashable
✗ Incorrect
AnyHashable erases the type of any hashable value, allowing heterogeneous collections.
Explain type erasure in Swift and why it is useful.
Think about protocols with associated types and how you can use different types together.
You got /4 concepts.
Describe how you would implement a type-erased wrapper for a protocol with an associated type.
Focus on forwarding calls and hiding the underlying type.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of type erasure in Swift?
easy
A. To convert classes into structs automatically
B. To create new types from existing ones
C. To improve runtime performance by avoiding protocols
D. To hide specific types behind a common interface
Solution
Step 1: Understand type erasure concept
Type erasure is used to hide the concrete underlying type and expose a common interface.
Step 2: Identify the main purpose
This allows different types to be used uniformly without exposing their specific details.
Final Answer:
To hide specific types behind a common interface -> Option D
Quick Check:
Type erasure = hiding types behind interface [OK]
Hint: Type erasure hides types to unify usage [OK]
Common Mistakes:
Confusing type erasure with type conversion
Thinking it improves performance directly
Assuming it creates new types
2. Which of the following is the correct syntax to create a type-erased wrapper for a protocol MyProtocol?
easy
A. struct AnyMyProtocol: MyProtocol { private let _base: any MyProtocol }
B. struct AnyMyProtocol<T>: MyProtocol { private let _base: T }
C. struct AnyMyProtocol: MyProtocol { private let _base: MyProtocol }
D. struct AnyMyProtocol: MyProtocol { private let _base: some MyProtocol }
Solution
Step 1: Recall type erasure syntax
Type erasure uses a struct that conforms to the protocol and stores an instance of any Protocol to hide the concrete type.
Step 2: Identify correct syntax
struct AnyMyProtocol: MyProtocol { private let _base: any MyProtocol } uses any MyProtocol which is the correct way to store an existential type in Swift 5.7+.
Final Answer:
struct AnyMyProtocol: MyProtocol { private let _base: any MyProtocol } -> Option A
Quick Check:
Use any Protocol for type erasure storage [OK]
Hint: Use 'any Protocol' to store erased type [OK]
B. Cannot assign generic method to closure with Any parameter
C. Cannot use associatedtype in protocol
D. Function printItem has wrong return type
Solution
Step 1: Analyze closure assignment
The closure _print expects (Any) -> Void but printer.printItem expects (P.Item) -> Void, which is a mismatch.
Step 2: Understand type erasure limitation
Associated types prevent direct assignment because the types differ; you cannot assign a generic method to a closure with Any parameter.
Final Answer:
Cannot assign generic method to closure with Any parameter -> Option B
Quick Check:
Generic method ≠ closure with Any parameter [OK]
Hint: Generic methods can't be assigned to Any closures directly [OK]
Common Mistakes:
Thinking protocol conformance is missing
Confusing associatedtype usage
Assuming return type mismatch
5. You want to create a type-erased wrapper for a protocol DataSource with an associated type Item and a method func fetch() -> [Item]. Which approach correctly applies type erasure to allow storing different DataSource implementations in a single array?
hard
A. Create a struct AnyDataSource with a private closure _fetch: () -> [Any] and cast results inside
B. Use a generic struct AnyDataSource<T> storing DataSource directly
C. Create a struct AnyDataSource with a private closure _fetch: () -> [Item] and use type erasure with a generic initializer
D. Use protocol inheritance to remove associated type
Solution
Step 1: Understand associated type challenge
Protocols with associated types cannot be used directly in collections because the type varies.
Step 2: Apply type erasure pattern
Create a struct with a private closure returning [Item], and initialize it generically to wrap any DataSource, hiding the concrete type.
Step 3: Evaluate options
Create a struct AnyDataSource with a private closure _fetch: () -> [Item] and use type erasure with a generic initializer correctly uses a generic initializer and closure with [Item], preserving type safety and enabling storage in arrays.
Final Answer:
Create a struct AnyDataSource with a private closure _fetch: () -> [Item] and use type erasure with a generic initializer -> Option C
Quick Check:
Type erasure with generic init and closure = Create a struct AnyDataSource with a private closure _fetch: () -> [Item] and use type erasure with a generic initializer [OK]
Hint: Use generic init and closure returning [Item] for erasure [OK]
Common Mistakes:
Casting to [Any] loses type safety
Using generic struct prevents uniform storage
Trying to remove associated type via inheritance
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.