Muzahid
Muzahid

Reputation: 5186

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?

Upvotes: 1

Views: 68

Answers (3)

Vinod Vishwanath
Vinod Vishwanath

Reputation: 5901

Objected-Oriented Programming 101.

You're passing the same instance of address to both objects. Essentially, it means that John and Adam have the same address, and when that address changes, both their addresses (which is just one object) change.

If you want to use Address as a value type as opposed to a reference type, you can convert Address to a struct, and everything else will just work:

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

Value types, like Int and Double (and structs, like we just saw) are only identified by a value, and not by their underlying memory address.

Upvotes: 3

Sandeep
Sandeep

Reputation: 21154

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.

Upvotes: 4

James
James

Reputation: 1036

You're actually passing in a pointer of the Address to your Persons.

Since both of the persons point to the same Address, changing the address of Person1 will also change it of Person2.

Upvotes: 1

Related Questions