Using NSArray as function parameter

583 views Asked by At

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.

3

There are 3 answers

0
Andriy Gordiychuk On BEST ANSWER

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)
}
1
NRitH On

Don't use NSArray. Swift wants its arrays to be typed, so declare it to be an [NSNumber] instead. And while it's by an error, your for loop should use the for...in construct instead of using an index variable.

1
Kametrixom On
func sumaEnteros(enteros : [Int]) -> Int {
    var result = 0
    for val in enteros{
        result += val
    }
    return result
}

sumaEnteros([1, 2, 3])

or simpler:

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

Don't use NSArray