Skip to content

Instantly share code, notes, and snippets.

@memfrag
Last active February 8, 2019 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save memfrag/b52349c0fa49c4e4e368 to your computer and use it in GitHub Desktop.
Save memfrag/b52349c0fa49c4e4e368 to your computer and use it in GitHub Desktop.
[Swift] Example of filter, map, and reduce
enum Faction {
case empire
case rebels
}
let characters: [(name: String, faction: Faction, episodes: [Int])] = [
(name: "Darth Maul", faction: .empire, episodes: [1]),
(name: "Han Solo", faction: .rebels, episodes: [4, 5, 6]),
(name: "Palpatine", faction: .empire, episodes: [1, 2, 3, 5, 6]),
(name: "R2-D2", faction: .rebels, episodes: [1, 2, 3, 4, 5, 6]),
(name: "Grand Moff Tarkin", faction: .empire, episodes: [6]),
(name: "Leia Organa", faction: .rebels, episodes: [4, 5, 6]),
(name: "Luke Skywalker", faction: .rebels, episodes: [4, 5, 6])
]
// Who in the list of characters from the rebel faction has appeared
// in the most episodes and how many?
// FILTER: Keep the rebels, throw away the imperial characters.
let rebels = characters.filter({ $0.faction == .rebels })
// MAP: Transform list of rebels to include the number of appearances
// instead of the list of episodes. Also throw away the faction.
let rebelsWithAppearances: Array<(name: String, appearances: Int)> = rebels.map({
(name: $0.name, appearances: $0.episodes.count)
})
// REDUCE: Reduce the list to only the rebel character with the
// most number of appearances.
let defaultRebel = (name: "Nobody", appearances: 0)
let (name, mostAppearances) = rebelsWithAppearances.reduce(defaultRebel, {
($0.appearances > $1.appearances) ? $0 : $1
})
print("\(name) is the rebel with most appearances (\(mostAppearances)).")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment