How to write extensions for collection types

extension Array { func sum() -> Int { var sum = 0 for num in self { sum += num } return sum } } [1,2,3].sum() 

This code shows what I would like to do. Although I get an error on this line: sum += num . The error I get is: Could not find an overload for '+=' that accepts the supplied arguments .

I suppose the error has something to do with the fact that Array can contain many different types, not just Int, so it turns off. But how to fix it?

+6
source share
2 answers

All that is needed is an explicit cast to Int :

 extension Array { func Sum() -> Int { var sum = 0 for num in self { sum += (num as Int) } return sum } } println([1,2,3].Sum()) //6 
+3
source

There is currently no way to extend only a specific Array type ( Array<Int> ). This would be a great request for the bugreport.apple.com file.

In the meantime, you can do this (not in extension):

 func sum(ints:Int[]) -> Int { return ints.reduce(0, +) } 
+4
source

Source: https://habr.com/ru/post/970222/


All Articles