Created
December 5, 2014 20:07
-
-
Save jparishy/97fb0cd17b1a28873a01 to your computer and use it in GitHub Desktop.
My most common uses of map() & reduce()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// #1 Adding things up | |
// | |
let numbers = [Int](0..<10) | |
let total = numbers.reduce(0) { | |
return $0 + $1 | |
} | |
struct Person { | |
let name: String | |
let age: Int | |
} | |
let people = [ | |
Person(name: "Katie", age: 23), | |
Person(name: "Bob", age: 21), | |
Person(name: "Rachel", age: 33), | |
Person(name: "John", age: 27), | |
Person(name: "Megan", age: 15) | |
] | |
let ages: [Int] = people.map { return $0.age } | |
let agesTotal = ages.reduce(0) { return $0 + $1 } | |
let averageAge = agesTotal / ages.count | |
// | |
// Combining booleans | |
// | |
let booleans = [ | |
false, | |
false, | |
true, | |
false, | |
true, | |
true | |
] | |
let allTrue = booleans.reduce(true) { | |
(sum, next) in | |
return sum && next | |
} | |
let allFalse = booleans.reduce(true) { | |
(sum, next) in | |
return sum && !next | |
} | |
let anyTrue = booleans.reduce(false) { | |
(sum, next) in | |
return sum || next | |
} | |
let anyFalse = booleans.reduce(false) { | |
(sum, next) in | |
return sum || !next | |
} | |
struct OptionState { | |
let title: String | |
let selected: Bool | |
} | |
let optionStates = [ | |
OptionState(title: "Objective-C", selected: true), | |
OptionState(title: "Swift", selected: true), | |
OptionState(title: "Haskell", selected: false), | |
OptionState(title: "Ruby", selected: true) | |
] | |
let allSelected = optionStates.reduce(true) { | |
return $0 && $1.selected | |
} | |
let anySelected = optionStates.reduce(false) { | |
return $0 || $1.selected | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment