Sobes.tech
Junior — Senior

What will be printed in the console?

livecode

Task condition

The task considers a simple Person structure in Swift, containing a single property — name. Three instances of the structure are created, then they are placed into an array people. Next, the name of the first object is changed, and then the array is printed to the console. After that, the name of the first element of the array is changed again, and the array is printed once more. It is necessary to understand how the values in the array will change after modifying the variables, considering that structures in Swift are passed by value.

import Foundation

struct Person {
    var name: String

    init(name: String) {
        self.name = name
    }
}

func main() {
    var first = Person(name: "Alice")
    let second = Person(name: "Bob")
    let third = Person(name: "Charlie")

    var people = [first, second, third] as [Person]

    first.name = "John"

    for p in people {
        print(p.name)
    }

    people[0].name = "John2"

    for p in people {
        print(p.name)
    }
}

main()