A generic subscript allows you to define a subscript that can work with any type, using a placeholder type parameter. This makes the subscript flexible and reusable for different data types.
Click to reveal answer
beginner
How do you declare a generic subscript in Swift?
You declare a generic subscript by adding a generic type parameter in angle brackets <> after the subscript keyword, like: subscript<T>(index: Int) -> T { ... }
Click to reveal answer
intermediate
Why use generic subscripts instead of regular subscripts?
Generic subscripts let you write one subscript that works with many types, reducing code duplication and increasing flexibility. Regular subscripts work with fixed types only.
Click to reveal answer
intermediate
Can a generic subscript have multiple generic parameters?
Yes, a generic subscript can have multiple generic parameters, just like generic functions. For example: subscript(key: T) -> U { ... }
Click to reveal answer
beginner
Give a simple example of a generic subscript in Swift.
Example:<br><code>struct Box {<br> private var items = [Any]()<br> subscript<T>(index: Int) -> T? {<br> get { items[index] as? T }<br> set { if let newValue = newValue { items[index] = newValue } }<br> }<br>}</code><br>This subscript can get or set items of any type safely.
Click to reveal answer
What does the <T> mean in a generic subscript declaration in Swift?
AIt limits the subscript to only Int types.
BIt declares a placeholder type that can be any type.
CIt specifies the subscript returns a tuple.
DIt is a syntax error in Swift.
✗ Incorrect
The declares a generic type parameter, meaning the subscript can work with any type T.
Can a generic subscript return different types depending on the caller?
AYes, the caller decides the type by specifying it.
BNo, the return type is fixed.
COnly if the subscript is static.
DOnly if the subscript uses Int as generic type.
✗ Incorrect
Generic subscripts can return different types because the caller specifies the type when using the subscript.
Which keyword is used to define a subscript in Swift?
Afunc
Bindex
Csubscript
Dget
✗ Incorrect
The keyword 'subscript' defines a subscript in Swift.
Is it possible to have a generic subscript with constraints on the generic type?
AYes, you can add constraints like <T: Equatable>.
BNo, generic subscripts cannot have constraints.
COnly for classes, not structs.
DOnly if the subscript is private.
✗ Incorrect
Generic subscripts can have constraints on their generic types, just like generic functions.
What happens if you try to access a generic subscript with a type that does not match the stored data?
AIt causes a compile-time error.
BIt automatically converts the type.
CIt always returns a default value.
DIt returns nil if optional or causes a runtime error.
✗ Incorrect
If the type does not match, optional generic subscripts return nil; otherwise, it may cause a runtime error.
Explain what a generic subscript is and why it is useful in Swift.
Think about how generics help functions work with many types.
You got /3 concepts.
Write a simple Swift struct with a generic subscript that stores and retrieves values of any type.
Use an array of Any and cast inside the subscript.
You got /4 concepts.
Practice
(1/5)
1. What is the main benefit of using generic subscripts in Swift?
easy
A. They allow subscripts to accept different types as keys or indexes.
B. They make subscripts run faster by using fixed types only.
C. They restrict subscripts to only integer indexes.
D. They automatically convert all keys to strings.
Solution
Step 1: Understand generic subscripts purpose
Generic subscripts let you write one subscript that works with many types of keys or indexes.
Step 2: Compare options with this purpose
Only They allow subscripts to accept different types as keys or indexes. correctly states that generic subscripts accept different types as keys or indexes.
Final Answer:
They allow subscripts to accept different types as keys or indexes. -> Option A
4. Identify the error in this generic subscript code and choose the fix:
struct Container {
private var data = [Int: String]()
subscript<T>(key: T) -> String? {
get { data[key] }
set { data[key] = newValue }
}
}
medium
A. Change dictionary to [T: String] to match generic key type.
B. Add type constraint to subscript declaration.
C. Change subscript to subscript(key: Int) -> String? to match dictionary key type.
D. No error; code works as is.
Solution
Step 1: Check dictionary key type vs subscript key type
Dictionary keys are Int, but subscript uses generic T which can be any type.
Step 2: Identify mismatch causing error
Accessing data[key] fails because key is T, not necessarily Int. Fix is to restrict subscript key to Int.
Final Answer:
Change subscript to subscript(key: Int) -> String? to match dictionary key type. -> Option C
Quick Check:
Subscript key type must match dictionary key type [OK]
Hint: Subscript key type must match dictionary key type [OK]
Common Mistakes:
Assuming generic T works without constraints
Trying to change dictionary type without reason
Ignoring type mismatch errors
5. Given a struct that stores values with keys of any Hashable type, how can you implement a generic subscript to safely get and set values? Choose the best approach.
hard
A. Use separate dictionaries for each key type and switch inside the subscript.
B. Use a dictionary with keys of type AnyHashable and cast keys inside the subscript.
C. Use a dictionary with keys of type String only and convert all keys to String.
D. Use a generic dictionary [T: Any] without constraints and force cast keys.
Solution
Step 1: Understand requirement for any Hashable key
To store values with keys of any Hashable type, use a dictionary with keys of type AnyHashable.
Step 2: Implement generic subscript with safe casting
Use generic subscript with key of type T: Hashable, convert key to AnyHashable for dictionary access, ensuring type safety.
Final Answer:
Use a dictionary with keys of type AnyHashable and cast keys inside the subscript. -> Option B