0
0
Swiftprogramming~5 mins

Generic subscripts in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
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.
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.
Which keyword is used to define a subscript in Swift?
Afunc
Bindex
Csubscript
Dget
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.
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.
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.