Created
June 27, 2018 03:05
-
-
Save gallaugher/f0bdb047854937d92e8293b224dd2dc4 to your computer and use it in GitHub Desktop.
Steps to shrink .reduce code for finding an average of an array of Ints
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
| var scores = [83, 85, 90, 100] | |
| // The full syntax .reduce above does the same thing as this one-liner: | |
| let total = scores.reduce(0, {$0 + $1}) | |
| // Swift even allows us to eliminate the closure, replacing it with an operator and automatically assuming it’ll apply the current accumulating value on the left of the operator, and the next accumulating value to the right | |
| let anotherWayToTotal = scores.reduce(0, +) | |
| // You can even do the entire calculation in a single line, although it starts to get more difficult to read: | |
| let average = Double(scores.reduce(0, +)) / Double(scores.count) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment