I have the following problem:
When I change the value of an array in a for-loop the array is not saved with this new value.
Example:
Code Block swift var numbers = [2, 3, 4, 6, 9] let theNumber = 4 print("Numbers old: \(numbers)") for var number in numbers { if number == theNumber { print("Numbers are identical") number = 10 /*save the changed number in array*/ } } print("Numbers new: \(numbers)")
The console output is:
So the value of the array is not changed.Numbers old: [2, 3, 4, 6, 9]
Numbers are identical
Numbers new: [2, 3, 4, 6, 9]
How to modify the code so that the value of the array is changed?
Is there an easy way to do so?
Help is very welcome!
Thank you!
Right. This is expected. When you use a var in a for loop like this, you can a read-write copy of the number value but it’s not bound to the original numbers array.So the value of the array is not changed.
The easiest way to fix your code is to iterate over the indexes:How to modify the code so that the value of the array is changed?
Code Block for i in numbers.indices { if numbers[i] == theNumber { numbers[i] = 10 } }
However, the best (IMO, obviously :-) way to fix it is to avoid the for loop entirely:
Code Block let newNumbers = numbers.map { number in number == theNumber ? 10 : number }
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"