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 constants1struct Person {2 let name: String3 let age: Int4 let city: String5}6 // Four people; the array type [Person] is inferred7let 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 name16 .map { $0.name } // Sorts the names alphabetically17 .sorted() // Joins them into one String: "Alice, Diana"18 .joined(separator: ", ")19 // Prints NYC adults: Alice, Diana20print("NYC adults: \(nycAdults)")Output
NYC adults: Alice, Diana
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