Collection Operations Chain in Swift

Level 5416 keystrokes

filter, map, sorted and joined are chained to turn a list of people into one string. Only people in NYC aged 25 or over are kept, their names are sorted and joined, giving NYC adults: Alice, Diana.

Swift code

// Simple record with three constants
1struct Person {
2 let name: String
3 let age: Int
4 let city: String
5}
6
// Four people; the array type [Person] is inferred
7let people = [
8 Person(name: "Alice", age: 28, city: "NYC"),
9 Person(name: "Bob", age: 35, city: "LA"),
10 Person(name: "Charlie", age: 22, city: "NYC"),
11 Person(name: "Diana", age: 31, city: "NYC")
12]
13
14let nycAdults = people
// Keeps NYC residents aged 25+: Alice and Diana (Charlie is 22)
15 .filter { $0.city == "NYC" && $0.age >= 25 }
// Turns each Person into its name
16 .map { $0.name }
// Sorts the names alphabetically
17 .sorted()
// Joins them into one String: "Alice, Diana"
18 .joined(separator: ", ")
19
// Prints NYC adults: Alice, Diana
20print("NYC adults: \(nycAdults)")

Output

NYC adults: Alice, Diana
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.

  • "× 22
  • :× 17
  • ,× 12
  • (× 8
  • )× 8
  • .× 7
  • =× 5
  • {× 3
  • }× 3
  • $× 3

More Swift examples at level 5

← Swift typing practice