Is it possible to extend an generic class for a specialised/constructed generic type? I would like to extend Int Arrays with a method to calculate the sum of its elements.
It is possible to return a real sum-value after you have tested for the int-type in sum()
. Doing so I would solve the problem as follows:
import Cocoa
extension Array {
func sum() -> Int {
if !(self[0] is Int) { return 0; }
var sum = 0;
for value in self { sum += value as Int }
return sum;
}
}
let array = [1,2,3,4,5]
array.sum() // =15
let otherArray = ["StringValue"]
otherArray.sum() // =0