Bird
Raised Fist0
Swiftprogramming~10 mins

Generic subscripts in Swift - Step-by-Step Execution

Choose your learning style10 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.

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

  1. Step 1: Understand generic subscripts purpose

    Generic subscripts let you write one subscript that works with many types of keys or indexes.
  2. 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.
  3. Final Answer:

    They allow subscripts to accept different types as keys or indexes. -> Option A
  4. Quick Check:

    Generic subscripts = flexible key types [OK]
Hint: Generic subscripts = flexible keys/indexes [OK]
Common Mistakes:
  • Thinking generic subscripts improve speed
  • Assuming subscripts only accept integers
  • Believing keys auto-convert to strings
2. Which of the following is the correct syntax to declare a generic subscript in Swift?
easy
A. subscript(index: T) -> String { get }
B. func subscript<T>(index: T) -> String { get }
C. subscript<T>(index: Int) -> T { get }
D. subscript<T>(index: T) -> String { get }

Solution

  1. Step 1: Recall generic subscript syntax

    Generic subscripts use subscript<T>(index: T) -> ReturnType syntax.
  2. Step 2: Check each option

    subscript<T>(index: T) -> String { get } matches the correct syntax. func subscript<T>(index: T) -> String { get } wrongly uses func. subscript(index: T) -> String { get } misses generic parameter declaration. subscript<T>(index: Int) -> T { get } has mismatched types.
  3. Final Answer:

    subscript<T>(index: T) -> String { get } -> Option D
  4. Quick Check:

    Generic subscript syntax = subscript<T> [OK]
Hint: Generic subscript uses subscript<T>(index: T) syntax [OK]
Common Mistakes:
  • Using func instead of subscript
  • Omitting generic parameter <T>
  • Mismatching parameter and return types
3. What will be the output of this Swift code?
struct Box {
    private var values = [String: Any]()
    subscript<T>(key: String) -> T? {
        get { values[key] as? T }
        set { values[key] = newValue }
    }
}

var box = Box()
box["age"] = 30
box["name"] = "Alice"
print(box["age"] as Int?, box["name"] as String?)
medium
A. Optional(30) Optional("Alice")
B. 30 Alice
C. nil nil
D. Compilation error

Solution

  1. Step 1: Understand subscript behavior

    The subscript stores values in a dictionary with String keys and Any values, casting on get.
  2. Step 2: Analyze stored values and prints

    "age" stores 30 (Int), "name" stores "Alice" (String). The print casts them back to Int? and String?, so output shows optionals.
  3. Final Answer:

    Optional(30) Optional("Alice") -> Option A
  4. Quick Check:

    Generic subscript returns optional cast values [OK]
Hint: Generic subscript returns optional cast values [OK]
Common Mistakes:
  • Expecting non-optional output
  • Confusing dictionary storage with direct types
  • Assuming compilation error due to Any type
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

  1. Step 1: Check dictionary key type vs subscript key type

    Dictionary keys are Int, but subscript uses generic T which can be any type.
  2. 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.
  3. Final Answer:

    Change subscript to subscript(key: Int) -> String? to match dictionary key type. -> Option C
  4. 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

  1. 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.
  2. 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.
  3. Final Answer:

    Use a dictionary with keys of type AnyHashable and cast keys inside the subscript. -> Option B
  4. Quick Check:

    AnyHashable dictionary + generic subscript = safe flexible keys [OK]
Hint: Use AnyHashable keys for flexible generic subscripts [OK]
Common Mistakes:
  • Using multiple dictionaries instead of one
  • Converting all keys to String losing type info
  • Force casting keys causing runtime errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard