Skip to content

Instantly share code, notes, and snippets.

@gallaugher
Created June 27, 2018 03:05
Show Gist options
  • Select an option

  • Save gallaugher/f0bdb047854937d92e8293b224dd2dc4 to your computer and use it in GitHub Desktop.

Select an option

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
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