For loops error (Module2 Lesson 4 Challenge)

In the Lesson4 of Module 2, instructor said if I don’t need index I could just use
for element in array {
print(element)
}

However I got an error of not being change the value inside the array, can anyone help me to figure this one out?

Thank you.

When you use a loop in the manner you have done the error message gives you a clue as to what is going on.

In the case of your loop element is a constant and therefore cannot be changed.

For example it we were at the first iteration of the loop which is looking at the first item in the array and that item was the value of 4 then it is the same as saying:

let element = 4

Because that is a constant, it is immutable and you cannot change it.

In this case you have to use an index to access the array contents and increment the value so you should use:

for element in 0..<array.count {
    array[element] += 1
}

element is now an index value (effectively an integer) but it is still a constant and itself cannot be changed.

Isn’t using “for element in array” accessing the same element as array[element]?

so it’s not like python where you can just change the value inside a list using
for element in array:
element += 1
print(element)

In Swift, when you want to change the contents of an element in an array you have to do that via the array index. If you want to just display elements in a list then you can use:

let array = ["1", "2", "3", "4", "5", "6", "7"]   // and array of strings
for element in array {
    print(element)
}
1 Like