2

This will not happen if I just change the properties instead of replacing the reference to a new object.

Here is a class Person, which is a reference type,

class Person {
    var firstName: String
    var lastName: String
    init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
}

Here is an instance of Person,

var someone = Person(firstName: "Johnny", lastName: "Appleseed")

then I make an array containing values of type Person

var lotsOfPeople = [someone, someone, someone]

I suppose lotsOfPeople containing 3 references to someone. But if I change the third value in lotsOfPeople,

lotsOfPeople[2] = Person(firstName: "Lucy", lastName: "Swift")

someone itself isn't changed.

print(someone.firstName) // Johnny

I think it means lotsOfPeople[2] is not a reference to someone. How could this happen?

0

1 Answer 1

4

The problem is that you are replacing the reference at lotsOfPeople[2] to point to a new object. That is why the original Person is not changed.

If you did lotsOfPeople[2].firstName = "Lucy" then it would change.

Or do:

let person = lotsOfPeople[2]
person.firstName = "Lucy"

then you would also see the original change.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.