Search code examples
iosswift3for-in-loop

For in loop. How does it works?




I need an explanation about for in loops in swift. Let's consider the following example.

public struct Person {
   let name: String
   let age: Int
   var surname: String?
}

var persons: [Person] = []

for i in 0...5 {
   let person = Person("test", i)
   persons.append(person)
}


And here is my question.
Why this won't work

//first for in loop
for var person in persons {
   person.surname = "surname"
}

print(persons[0].surname) // output: nil 

And this does

// second for in loop
for i in 1...persons.count {
   persons[i].surname = "surname"
}

print(persons[0].surname) // output: 'surname' 


I can see that first for in loop is working on copy person object because I can see output while I'm in the loop. But why are we working on copy? And can I somehow change value of person object in the first for in loop?


Solution

  • Reason

    Since Person is a struct, the value logic is applied.

    Example

    It means that when you write

    var person = anotherPerson
    

    You are creating a copy. So changing one value does not affect the other value.

    Exactly the same thing happens in your for in

    for var person in persons {
        person.surname = "surname"
    }
    

    Solution

    Finally you can get a new array of persons with the new surname writing this

    let personsWithSurname = persons.map { person -> Person in
        var person = person
        person.surname = "surname"
        return person
    }