Junior — Middle
What is the difference between reference and value types in Swift?
sobes.tech AI
Answer from AI
In Swift, data types are divided into value types and reference types.
-
Value types (for example,
struct,enum, tuples) are copied when assigned or passed to a function. This means each variable has its own independent copy of the data. -
Reference types (classes
class) pass a reference to the same object in memory when assigned or passed. Changes through one reference will be visible through others.
Example:
struct Point {
var x: Int
var y: Int
}
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var p1 = Point(x: 0, y: 0)
var p2 = p1
p2.x = 10
print(p1.x) // 0, because p2 is a copy of p1
var person1 = Person(name: "Alice")
var person2 = person1
person2.name = "Bob"
print(person1.name) // Bob, because person2 and person1 refer to the same object
Thus, the difference is that value types are copied, while reference types pass a reference to the same object.