Swift will actually allow you to declare the iterator symbol as a var
instead of an implicit let
:
for var number in 0..<11 {
print("original: \(number)")
if number.isMultiple(of: 2) {
number -= 1
}
print("changed: \(number)")
}
Prints:
original: 0
changed: -1
original: 1
changed: 1
original: 2
changed: 1
original: 3
changed: 3
original: 4
changed: 3
original: 5
changed: 5
original: 6
changed: 5
original: 7
changed: 7
original: 8
changed: 7
original: 9
changed: 9
original: 10
changed: 9
I don't really see much use for it, to be honest, but you can do it. You can see that even though you change number
inside the for in
loop, the next time through the loop it is set to whatever value it would have if you didn't change it. So, what's the point?
Even with something a little more complex than simple numbers, you can use var
instead of let
, but again I'm hard-pressed to think of a good use for it.
struct Person {
let id = UUID()
var name: String
}
let people: [Person] = [
Person(name: "Shelley Winters"),
Person(name: "Ryan Beckwith"),
Person(name: "Amy Chilton"),
]
for var person in people {
if person.name == "Amy Chilton" {
person.name = "Amy Beckwith-Chilton"
}
print(person)
}
print(people)
And note, too, that the Person
items in the people
array will remain unchanged, regardless of what you do in the for in
loop.