This can be achieved using protocol extensions (See The Swift Programming Language: Protocols for more information).
To sum just Int
s you could do:
extension Sequence where Iterator.Element == Int {
var sum: Int {
return reduce(0, +)
}
}
Usage:
let nums = [1, 2, 3, 4]
print(nums.sum) // Prints: "10"
Or, for something more generic (Swift 5) you can use AdditiveArithmetic
:
extension Sequence where Iterator.Element: AdditiveArithmetic {
var sum: Iterator.Element {
return reduce(.zero, +)
}
}
For Swift 4 and below, you can use what @Wes Campaigne suggested and create an Addable
protocol:
protocol Addable {
init()
func + (lhs: Self, rhs: Self) -> Self
}
extension Int : Addable {}
extension Double: Addable {}
extension String: Addable {}
...
Next, extend Sequence
to add sequences of Addable
elements:
extension Sequence where Iterator.Element: Addable {
var sum: Iterator.Element {
return reduce(Iterator.Element(), +)
}
}
Usage:
let doubles = [1.0, 2.0, 3.0, 4.0]
print(doubles.sum) // Prints: "10.0"
let strings = ["a", "b", "c"]
print(strings.sum) // Prints: "abc"