Sobes.tech
Junior

What is the difference between reference types and value types?

sobes.tech AI

Answer from AI

A reference stores an address in memory pointing to the data stored there. In fact, a variable holding a reference only owns this address, not the data itself. Assigning a reference type to a variable copies the reference, not the data. Changes to the data pointed to by the reference are reflected in all variables holding that reference.

A value type directly stores the data itself. Assigning a value type to a variable copies the data itself. Changes in one variable of a value type do not affect other variables that received this copy.

Attribute Reference Type Value Type
Storage Reference to data Data itself
Assignment Copying the reference Copying the data
Modification Affects all references Does not affect copies
Placement Heap Stack
Deallocation ARC / Garbage collector Automatically upon scope exit
Examples in Swift class, closure struct, enum, tuple, basic types (Int, Bool, String, etc.)
// Example of a reference type (class)
class ReferenceType {
    var value: Int
    init(value: Int) {
        self.value = value
    }
}

let ref1 = ReferenceType(value: 10)
let ref2 = ref1 // Reference is copied
ref2.value = 20 // Data pointed to by ref1 and ref2 is changed
print(ref1.value) // Output: 20
print(ref2.value) // Output: 20

// Example of a value type (struct)
struct ValueType {
    var value: Int
}

var val1 = ValueType(value: 10)
var val2 = val1 // Data is copied
val2.value = 20 // Only data in val2 is changed
print(val1.value) // Output: 10
print(val2.value) // Output: 20
What is the difference between reference types and… - sobes.tech