Search code examples
iosxcodeswiftswift-playground

Why have both objects changed automatically?


Here are the classes I defined

class Person{
  var name: String
  var address: Address

  init(name: String, address: Address){
    self.name = name
    self.address = address
  }

}

class Address {
  var city: String
  var country: String
  init(city: String, country: String){
    self.city = city
    self.country = country
  }
}


var address = Address(city: "New York", country: "USA")

    var person1 = Person(name: "John", address: address)

    var person2 = Person(name: "Adam", address: address)

    person1.address.city = "Washington"

    print(person1.address.city)

    print(person2.address.city)

I changed the city of person1 address but why did person2 city change, and how do I overcome the problem?


Solution

  • You are using class for your Address object. So, it pass by reference. Please look at this post for more detail on Value and Reference types, https://developer.apple.com/swift/blog/?id=10.

    In your case, if you change your Address from Class to Struct, everything works as you expected since, structs are passed by value.

    struct Address {
      let city: String
      let country: String
    }
    

    And, notice that you dont need any initializer. Struct by default creates initializer which you could use as you have done above.