Skip to content

Instantly share code, notes, and snippets.

@fisherds
Created December 11, 2014 17:26
Show Gist options
  • Select an option

  • Save fisherds/ec9ef650a6cd866897aa to your computer and use it in GitHub Desktop.

Select an option

Save fisherds/ec9ef650a6cd866897aa to your computer and use it in GitHub Desktop.
Code used in our Swift Playgrounds lecture
var values = [10, 5, 2, 8, 3, 6, 1, 1000]
// Verbose Closure
var numValuesOver5 = values.reduce(0, combine: {(runningTotal : Int, currentValue : Int) -> Int in
return currentValue > 5 ? runningTotal + 1 : runningTotal
})
// Closure parameter name shorthand and trailing closure
var numValuesOver9 = values.reduce(0) {
return $1 > 9 ? $0 + 1 : $0
}
// A Closure using a closure for a variable
func numValuesOverLimit(values : [Int], #limit : Int) -> Int {
return values.reduce(0) {
return $1 > limit ? $0 + 1 : $0
}
}
numValuesOverLimit(values, limit: 5)
numValuesOverLimit(values, limit: 9)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment