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.
In order for your function to work you should change your code to:
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
NSNumber
s which are contained in your array. If this is the case then you should change it to:This works well in case you REALLY need to have
NSArray
. However, if you can replace it with the Swift'sArray
type then you can make this function much-much simpler: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: