Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active March 6, 2025 18:16
Show Gist options
  • Save jakebromberg/a88a64d65e86847d09298615cfbada1a to your computer and use it in GitHub Desktop.
Save jakebromberg/a88a64d65e86847d09298615cfbada1a to your computer and use it in GitHub Desktop.
import Foundation
extension Collection {
subscript<T>(_ keyPath: KeyPath<Element, T>) -> [T] {
return map { $0[keyPath: keyPath] }
}
}
struct Person {
let firstName: String
}
let expectedFirstNames = ["Alice", "Bob", "Charlie"]
let people = expectedFirstNames.map(Person.init)
assert(expectedFirstNames == people[\.firstName])
let counts = people[\.firstName.count]
assert(expectedFirstNames.map(\.count) == counts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment