Junior — Middle
What are the differences between value types and reference types in programming?
sobes.tech AI
Answer from AI
Value types and reference types differ in how they store and pass data.
-
Value types are stored directly in the variable's memory. When assigned or passed, the actual value is copied. Changes to the copy do not affect the original. In Swift, value types include structures (struct), enumerations (enum), and tuples.
-
Reference types are stored in the heap, and the variable contains a reference to the object. When assigned, only the reference is copied, not the object. Changes through one reference are reflected in all references. In Swift, classes (class) are reference types.
Example:
struct Point {
var x: Int
var y: Int
}
class Person {
var name: String
init(name: String) { self.name = name }
}
var p1 = Point(x: 1, y: 2)
var p2 = p1
p2.x = 10
print(p1.x) // 1 — copy did not change
var person1 = Person(name: "Alice")
var person2 = person1
person2.name = "Bob"
print(person1.name) // Bob — both variables refer to the same object