Skip to content

Instantly share code, notes, and snippets.

@islandjoe
Created May 31, 2018 14:28
Show Gist options
  • Save islandjoe/dc8227d9f983a5b1ca8aac5b36eb05b3 to your computer and use it in GitHub Desktop.
Save islandjoe/dc8227d9f983a5b1ca8aac5b36eb05b3 to your computer and use it in GitHub Desktop.
Reducing in Swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8]

Function as argument

func reducedSum(sum: Int, element: Int) -> Int {
  return sum + element
}
let sum = numbers.reduce(0, reducedSum)
//-> 36

Closure

let product = numbers.reduce(1) { (product: Int, element: Int)-> Int in
  return product * element
}
//-> 40320

Shorthand argument

let difference = numbers.reduce(0) { $0 - $1 }
//-> -36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment