Key Path in Swift

Level 5406 keystrokes

A key path such as \.name refers to a property of a type without reading it yet. Passing key paths to map extracts the names and the nested cities, printing ["Alice", "Bob"] and ["Tokyo", "Paris"].

Swift code

1struct Person {
2 var name: String
3 var age: Int
// A nested struct property
4 var address: Address
5}
6
7struct Address {
8 var city: String
9 var country: String
10}
11
// Two people with different addresses
12let people = [
13 Person(name: "Alice", age: 30, address: Address(city: "Tokyo", country: "Japan")),
14 Person(name: "Bob", age: 25, address: Address(city: "Paris", country: "France"))
15]
16
// A key path can be used as a function: same as map { $0.name }
17let names = people.map(\.name)
// Key paths can go through nested properties
18let cities = people.map(\.address.city)
// Prints ["Alice", "Bob"]
19print(names)
// Prints ["Tokyo", "Paris"]
20print(cities)

Output

["Alice", "Bob"]
["Tokyo", "Paris"]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • :× 15
  • "× 12
  • (× 8
  • )× 8
  • ,× 7
  • .× 5
  • =× 3
  • {× 2
  • }× 2
  • \× 2

More Swift examples at level 5

← Swift typing practice