9.2.2. Value vs. Reference
Another major difference between a struct and a class is how they behave when copied. Structs are 'value types,' and classes are 'reference types.'
(Structs) When you copy an instance of a struct from an existing instance, both instances work independently. For example:
struct User{
var name:String
}
//creating an instance of User...
var user1 = User(name: "John Smith")
//copying the instance to a new instance...
var user2 = user1
//changing the name in the copied instance...
user2.name = "Bob Smith"
print(
"""
User name of user1 = \(user1.name)
User name of user2 = \(user2.name)
"""
)
It prints:
We copied the instance user1 to another instance user2. When I changed the name in user2 it did not have any effect on user1. They worked independent to each other. The data of the instances are independent and separate to each other.
(Classes) However, classes are reference types. For example,
It prints:
Do you find the difference?
Here, we copied person1 to person2. But when we changed the name of person2, it also changed the name of person1. So basically, the data is not separate for the two instances, they share the same data reference.
Reference Code
Last updated
Was this helpful?