Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
182: Generic Subscripts
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 toHashable. It should contain aStringidentifier. - Implement a
GameStatRegistryclass with a private storage dictionary[String: Any]. - Add a generic subscript to
GameStatRegistrythat takes aStatKey<T>and returnsT?. - Define three static keys:
score(Int),health(Double), andisAlive(Bool). - In your main code, set values for these keys and retrieve them without using any manual
as?casting at the call site.
There are no comments for now.