Search code examples
swiftswift-playground

Using NSArray as function parameter


I'm trying to add all elements of one NSArray using the NSNumber in for. Why this code doesn't work in playground example?

func sumaEnteros(enteros : NSArray) -> Int {
    var result = 0
    for NSNumber i in enteros{
        result += enteros.indexOfObject(i)
    }
    return result
}

Param "enteros" is marked as error in playground.


Solution

  • In order for your function to work you should change your code to:

    func sumaEnteros(enteros : NSArray) -> Int {
        var result = 0
        for i in enteros{
            result += enteros.indexOfObject(i)
        }
        return result
    }
    

    However, I am not actually sure that it will achieve what you want. This function will sum up all the indexes in your array. For example, for an array containing 5 elements it will output 0+1+2+3+4 = 10.

    Judging by your question what you want instead is to sum up all NSNumbers which are contained in your array. If this is the case then you should change it to:

    func sumaEnteros(enteros : NSArray) -> Int {
        var result = 0
        for i in enteros{
            if let number = i as? NSNumber {
                result += Int(number.intValue)
            }
        }
        return result
    }
    

    This works well in case you REALLY need to have NSArray. However, if you can replace it with the Swift's Array type then you can make this function much-much simpler:

    func sumaEnteros(enteros : [Int]) -> Int {
        return enteros.reduce(0, combine: +)
    }
    

    Finally, in case you actually want to sum up the indexes in your array (and not the numbers contained in it) then you should use the formula. Indexes always go as 0,1,2,3,4...n. This is a simple arithmetic progression. You can read about the formula for calculating its sum here.

    Using this formula your function would look like this:

    func sumaEnteros(enteros : NSArray) -> Int {
        return Int(Double(enteros.count)*Double(enteros.count-1)/2)
    }