Skip to Content
Course content

182: Generic Subscripts

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've been thinking about how we handle configuration objects in our projects. Usually, we end up with a dictionary of strings, and we spend half our time casting Any to Int or Bool and hoping we didn't typo the key. It's brittle. I want to build something a bit more robust—a SettingsStore—where the subscript feels native regardless of what we're using as a key.

The "String Key" Starting Point

Let's start with the obvious approach. I'll create a store that holds values in a dictionary and use a subscript to get them. This is the standard way most of us start.

class SettingsStore {
    private var storage: [String: Any] = [:]

    subscript(key: String) -> Any? {
        get { return storage[key] }
        set { storage[key] = newValue }
    }
}

let store = SettingsStore()
store["volume"] = 0.8
let vol = store["volume"] as? Double // Ugh, the casting again.

This works, but it's exactly what I wanted to avoid. Every time I access a value, I have to remember the type and perform a cast. It's not "type-safe"; it's just a wrapper around a dictionary. I want the store to be smarter about the keys it accepts.

Moving Toward Generic Keys

What if the store didn't just take strings? Some of my keys are enums, some are integers. If I make the SettingsStore itself generic, the subscript automatically becomes generic because it relies on the type defined at the class level.

Let's try making the key type a generic parameter K. But since I'm using this key in a dictionary, K needs to be Hashable.

class SettingsStore<K: Hashable> {
    private var storage: [K: Any] = [:]

    subscript(key: K) -> Any? {
        get { return storage[key] }
        set { storage[key] = newValue }
    }
}

enum AppSetting {
    case volume
    case username
}

let appStore = SettingsStore<AppSetting>()
appStore[.volume] = 0.8 // This feels much better.

Now we've solved the "typo" problem because we're using an enum. But we're still stuck with Any? as the return type. I'm still casting as? Double every time I read the volume. That's the real pain point.

The Limitation of Subscript Return Types

Here is where I hit a wall. I tried to do something like this:

// This will NOT compile
subscript<T>(key: K) -> T? { 
    get { return storage[key] as? T } 
}

Swift doesn't allow the subscript itself to introduce a new generic type parameter for the return value. The generics have to be defined at the type level (the class or struct). This means if I want a truly type-safe return, I can't just use a single generic store for everything if those things are different types.

The "Typed Key" Pattern

Since I can't make the subscript return a generic T on the fly, I have to change how I think about the key. Instead of the Store being generic, what if the Key itself carries the type information? This is a common pattern in high-end Swift libraries.

I'll create a SettingKey struct that remembers what type of value it's associated with. Then, I'll make the subscript generic based on the SettingKey.

struct SettingKey<Value>: Hashable {
    let name: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(name)
    }

    static func == (lhs: SettingKey, rhs: SettingKey) -> Bool {
        lhs.name == rhs.name
    }
}

class SettingsStore {
    private var storage: [String: Any] = [:]

    // The magic happens here. The subscript uses the type of the key 
    // to determine the return type.
    subscript<T>(key: SettingKey<T>) -> T? {
        get { return storage[key.name] as? T }
        set { storage[key.name] = newValue }
    }
}

Wait, I just said subscripts couldn't be generic. Why does this work? Look closely: the subscript is subscript<T>. In recent Swift versions, we can actually define generic parameters on the subscript itself, provided they are used in the arguments. By passing a SettingKey<T>, the compiler now knows exactly what T is. This is the "Generic Subscript" in its most powerful form.

Testing the Implementation

Let's see if this actually removes the casting from our call site.

let store = SettingsStore()

// We define our keys and their types upfront
extension SettingKey {
    static var volume: SettingKey<Double> = .init(name: "volume")
    static var username: SettingKey<String> = .init(name: "username")
}

store[.volume] = 0.75
store[.username] = "SwiftEngineer"

// Look! No 'as? Double' needed. The compiler knows it's a Double.
if let vol = store[.volume] {
    print("Volume is \(vol)") 
}

This is a massive win. The SettingKey acts as a witness for the type. The subscript sees that we passed a SettingKey<Double>, so it resolves the return type to Double?. It's clean, it's type-safe, and it moves the "danger" (the cast) inside the store's implementation where it's handled once, rather than everywhere in the UI code.




📋 Practical Task

Building a Type-Safe GameStat Registry

You are building a game engine and need a way to track various statistics (like playerScore, health, and isGameOver). Using a standard dictionary would require constant casting.

Your Goal: Implement a GameStatRegistry that uses generic subscripts to provide type-safe access to stats.

  • Create a StatKey<Value> struct that conforms to Hashable. It should contain a String identifier.
  • Implement a GameStatRegistry class with a private storage dictionary [String: Any].
  • Add a generic subscript to GameStatRegistry that takes a StatKey<T> and returns T?.
  • Define three static keys: score (Int), health (Double), and isAlive (Bool).
  • In your main code, set values for these keys and retrieve them without using any manual as? casting at the call site.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.