Skip to content

Instantly share code, notes, and snippets.

@avdyushin
Last active March 22, 2016 09:08
Show Gist options
  • Save avdyushin/65fe060fb18dd6a0baf5 to your computer and use it in GitHub Desktop.
Save avdyushin/65fe060fb18dd6a0baf5 to your computer and use it in GitHub Desktop.
Functional Swift Cheat Sheet
// Product of list
func product(list: [Double]) -> Double {
return list.reduce(1, combine: *)
}
// Sum of list
func sum(list: [Int]) -> Int {
return list.reduce(0, combine: +)
}
// Sum of filtered list
var sum = range(1..<1000).filter { ($0 % 3 == 0) || ($0 % 5 == 0) }.reduce(0, combine: +)
// Prime numbers generator
func primes(numbers: [Int]) -> [Int] {
guard !numbers.isEmpty else { return [] }
let first = numbers[0]
return [first] + primes(numbers[1..<numbers.count].filter { $0 % first > 0 })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment