Skip to content

Instantly share code, notes, and snippets.

@sindresorhus
Forked from fcanas/average.swift
Last active October 17, 2017 10:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sindresorhus/0f5981d6c583424ad6d963dba0d78616 to your computer and use it in GitHub Desktop.
Save sindresorhus/0f5981d6c583424ad6d963dba0d78616 to your computer and use it in GitHub Desktop.
Abstracted average function in Swift
extension Sequence where Element: ExpressibleByIntegerLiteral {
private func abstractAverage<T>(sum: (T, T) -> T, div: (T, T) -> T) -> T where Element == T {
var i: T = 0
var total: T = 0
for value in self {
total = sum(total, value)
i = sum(i, 1)
}
return div(total, i)
}
}
extension Sequence where Element: BinaryFloatingPoint {
func average() -> Element {
return abstractAverage(sum: +, div: /)
}
}
extension Sequence where Element: BinaryInteger {
func average() -> Element {
return abstractAverage(sum: +, div: /)
}
}
[1.0, 2.2, 3.0].average()
[1, 2, 3].average()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment