Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write extensions for collection types

Tags:

swift

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. Though i get an error on the this line: sum += num. The error i get is: Could not find an overload for '+=' that accepts the supplied arguments.

I assume the error has something to do with the fact that Array can contain lots of different types, not just Int, so it's bugging out. But how to fix?

like image 316
Alex Marchant Avatar asked Jun 03 '14 06:06

Alex Marchant


2 Answers

There isn't currently a way to extend only a particular type of Array (Array<Int> in this case). That'd be a great request to file at bugreport.apple.com

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

func sum(ints:Int[]) -> Int {
    return ints.reduce(0, +)
}
like image 133
Catfish_Man Avatar answered Nov 15 '22 07:11

Catfish_Man


All that's 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
like image 35
Jack Greenhill Avatar answered Nov 15 '22 07:11

Jack Greenhill