0
0
Swiftprogramming~10 mins

Generic subscripts in Swift - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Generic subscripts
Define generic subscript with placeholder T
Call subscript with specific type
Use T as the type for input/output
Return or set value of type T
End
A generic subscript uses a placeholder type T to get or set values of any type, decided when called.
Execution Sample
Swift
struct Box {
  private var items = [String: Any]()
  subscript<T>(key: String) -> T? {
    get { items[key] as? T }
    set {
      if let value = newValue {
        items[key] = value
      } else {
        items.removeValue(forKey: key)
      }
    }
  }
}
Defines a Box struct with a generic subscript to store and retrieve values of any type by key.
Execution Table
StepActionKeyType TValue StoredValue Retrieved
1Set value"age"Int30
2Set value"name"String"Alice"
3Get value"age"Int30
4Get value"name"String"Alice"
5Get value"age"Stringnil (type mismatch)
6Get value"height"Doublenil (key not found)
💡 No more operations, end of subscript usage.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
items[:]{"age": 30}{"age": 30, "name": "Alice"}{"age": 30, "name": "Alice"}{"age": 30, "name": "Alice"}{"age": 30, "name": "Alice"}{"age": 30, "name": "Alice"}
Key Moments - 3 Insights
Why does getting "age" as a String return nil?
Because the stored value for "age" is an Int, and the generic subscript tries to cast it to String, which fails (see step 5 in execution_table).
What happens if we try to get a value for a key that was never set?
The subscript returns nil because the key does not exist in the dictionary (see step 6 in execution_table).
How does the subscript know what type to return?
The caller specifies the type T when using the subscript, so the subscript tries to cast the stored value to that type.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what value is retrieved at step 4?
Anil
B"Alice"
C30
DType mismatch error
💡 Hint
Check the 'Value Retrieved' column for step 4 in the execution_table.
At which step does the subscript return nil due to a type mismatch?
AStep 5
BStep 3
CStep 6
DStep 2
💡 Hint
Look for 'nil (type mismatch)' in the 'Value Retrieved' column in execution_table.
If we add a new key "height" with value 1.75 (Double), what will be the value of items after setting it?
A{"age": 30, "name": "Alice"}
B{"height": 1.75}
C{"age": 30, "name": "Alice", "height": 1.75}
DNo change
💡 Hint
Refer to variable_tracker and how items changes after each set operation.
Concept Snapshot
Generic subscripts allow flexible get/set with any type.
Syntax: subscript<T>(key: KeyType) -> T? { get set }
Use type T as placeholder for input/output.
Caller decides T when accessing.
Returns nil if type mismatch or key missing.
Full Transcript
This example shows a Swift struct Box with a generic subscript. The subscript uses a placeholder type T to get or set values in a dictionary keyed by String. When setting, the value is stored as Any. When getting, the subscript tries to cast the stored value to type T. If the cast fails or the key is missing, it returns nil. The execution table traces setting and getting values of different types, showing how the generic subscript works step-by-step. The variable tracker shows how the internal dictionary changes after each set. Key moments clarify common confusions about type casting and missing keys. The visual quiz tests understanding of these steps. The concept snapshot summarizes the syntax and behavior of generic subscripts in Swift.