Understand the Differences Between Value Types & Reference Types
Written by Team Kodeco
In Swift, there are two main types of data types: value types and reference types.
- A value type is a data type whose value is stored directly in the memory.
- A reference type is a data type whose value is stored as a reference to the memory location where the actual value is stored.
Value types include basic data types such as Int, Float, Double, Bool and structs.
var a = 5
var b = a
b = 10
print(a) // Output: 5
print(b) // Output: 10
In this example, a
and b
are variables of value types and the value of b
is stored directly in the memory and changing the value of b
does not affect the value of a
Reference types include classes and closures.
class MyClass { var value = 0 }
var a = MyClass()
var b = a
b.value = 10
print(a.value) // Output: 10
print(b.value) // Output: 10
In this example, a
and b
are variables of reference types, and the value of b
is stored as a reference to the memory location where the actual value of a
is stored. Changing the value of b
affects the value of a
.