Swift & Concurrency (50 Qs)•Part 3: Runtime Internals, Swift 6 Safety & Systems Programming (25 - 35)
KeyPaths in Swift: Type-safe property referencing and functional composition.
senior LevelCode ExampleswiftRuntime Internals
In Simple Words: KeyPaths allow referencing properties as first-class un-invoked values:
swift
struct User { let name: String; var score: Int }
let nameKeyPath = User.name // KeyPath<User, String>
let user = User(name: "Elena", score: 95)
print(user[keyPath: nameKeyPath]) // "Elena"
// Functional mapping with KeyPaths:
let names = users.map(.name)
let sorted = users.sorted(by: .score)