For loops through the array

i wrote this code :slight_smile:
var array = [4 , 5 ,2 , 10 , 11]
for item in array {
array[item] = array[item] + 3
}
but i got this error :
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.

It’s because the item vairable holds the element in the array, not index.

From to your code:

This is the same as trying to write

array[4] = array[4] + 3
array[5] = array[5] + 3 // should crash here
array[2] = array[2] + 3
array[10] = array[10] + 3
array[11] = array[11] + 3

As you can see, you’re using the elements of the array as if they’re indices.
What you want is:

var array = [4 , 5 ,2 , 10 , 11]
for index in array.indices {
    array[index] = array[index] + 3
}

Which is then equivalent to

array[0] = array[0] + 3
array[1] = array[1] + 3
...

Since Array‘s index is of type Int, the program compiles and run.

P.S.
You can use += instead of adding value manually

var array = [4 , 5 ,2 , 10 , 11]
for index in array.indices {
    array[index] += 3
}

Even better, you can use functional api we have

var array = [4 , 5 ,2 , 10 , 11]
array = array.map { $0 + 3 }
7 Likes
Terms of Service

Privacy Policy

Cookie Policy