What is difference between value type and reference type in Swift?
In Swift, there are certain types called value types and others called reference types.
Struct, String, Array, Dictionary, and Set are value types.
Classes, functions, and closures are reference types.
Starting with String, a value type, check the following code:
let city = "Glasgow"
var anotherCity = city
anotherCity = "Edinburgh"
print("Value of city: \(city)")
print("Value of anotherCity: \(anotherCity)")
Output:
Value of city: Glasgow
Value of anotherCity: Edinburgh
Changing the value of anotherCity didn't affect the value of the variable city.
On the contrary, let's see the behavior of reference types, starting with a class:
class Car {
var name: String = ""
}
let car1 = Car()
car1.name = "Toyota Camry"
let car2 = car1
car2.name = "Mercedes Benz"
print("Car1 name: \(car1.name)")
print("Car2 name: \(car2.name)")
Output:
Car1 name: Mercedes Benz
Car2 name: Mercedes Benz
Since Car is a reference type, car2 points to the same instance as car1 — changing car2.name also changes what car1.name reports.