Skip to content

Instantly share code, notes, and snippets.

@gorozco58
Last active November 2, 2016 19:57
Show Gist options
  • Save gorozco58/779d45be6ca83fbcf30fb958368e966c to your computer and use it in GitHub Desktop.
Save gorozco58/779d45be6ca83fbcf30fb958368e966c to your computer and use it in GitHub Desktop.
This is an easy way to apply operation to generic numbers (Int, Float, Double, etc.)
protocol Math {
static func +(lhs: Self, rhs: Self) -> Self
static func *(lhs: Self, rhs: Self) -> Self
init()
}
//Extend all numbers you want to
extension Int : Math {}
extension Double : Math {}
extension Float : Math {}
extension Collection where Iterator.Element == Math {
func sum<T : Math>(_ x:T...) -> T {
return self.flatMap { $0 as? T }.reduce(x.reduce(T()) { $0 + $1}) { $0 + $1 }
}
func product<T : Math>(_ x:T...) -> T {
return self.flatMap { $0 as? T }.reduce(x.reduce(T()) { $0 * $1}) { $0 * $1 }
}
}
let a = [1,2,3].sum(10, 20, 30) //66
let b = [1.1,2.1,3.1].sum(1.0) //7.3
let c = [2,3].product(4)//24
let d = [1.3, 2.4].product(3.3, 4.5)//46.332
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment