Recall & Review
beginner
What is a generic subscript in Swift?
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: <br>
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: <br>
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?
✗ 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?
✗ 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?
✗ Incorrect
The keyword 'subscript' defines a subscript in Swift.
Is it possible to have a generic subscript with constraints on the generic type?
✗ 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?
✗ 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.