Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@usk2000
Created January 25, 2021 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usk2000/230d46869c9eba401978a8865d2f66fa to your computer and use it in GitHub Desktop.
Save usk2000/230d46869c9eba401978a8865d2f66fa to your computer and use it in GitHub Desktop.
sum and average functions for numeric array
import Foundation
extension Collection where Element == Int {
func sum() -> Int {
return reduce(0, +)
}
func average() -> Double {
let value = sum()
return Double(value) / Double(count)
}
}
extension Collection where Element == Float {
func sum() -> Float {
return reduce(0, +)
}
func average() -> Float {
return sum() / Float(count)
}
}
extension Collection where Element == Double {
func sum() -> Double {
return reduce(0, +)
}
func average() -> Double {
return sum() / Double(count)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment