Sobes.tech
Junior

Where are data types stored in Swift?

sobes.tech AI

Answer from AI

Data types in Swift are stored in two main memory areas: stack and heap.

Stack

  • Value types:
    • struct
    • enum
    • Basic types like Int, Double, Bool, String (short strings can be stored directly in the stack for optimization)
  • Data is stored directly in the stack in the order of function execution.
  • Allocation and deallocation of memory happen automatically and very quickly (LIFO - Last In, First Out).

Heap

  • Reference types:
    • class
    • Functions and closures
    • Objects (AnyObject)
  • Objects themselves are stored in the heap, while the stack only holds references to them.
  • Allocation and deallocation in the heap are dynamic and managed by the system (Automatic Reference Counting - ARC).
  • Access to data in the heap is indirect, through a pointer.

Features

  • Assigning a value type copies the entire value.
  • Assigning a reference type copies only the reference, both objects point to the same memory location in the heap.
  • ARC tracks the number of strong references to objects in the heap and automatically frees memory when no references remain.
// Example of a value type - stored in the stack
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 10, y: 20)
var p2 = p1 // Copies the entire value

p2.x = 30 // p1 remains unchanged
print("p1: \(p1), p2: \(p2)") // Output: p1: Point(x: 10, y: 20), p2: Point(x: 30, y: 20)

// Example of a reference type - stored in the heap
class Circle {
    var radius: Double

    init(radius: Double) {
        self.radius = radius
    }
}

var c1 = Circle(radius: 5.0)
var c2 = c1 // Only the reference is copied

c2.radius = 10.0 // c1 also changes, as both point to the same object in the heap
print("c1.radius: \(c1.radius), c2.radius: \(c2.radius)") // Output: c1.radius: 10.0, c2.radius: 10.0
Where are data types stored in Swift? — iOS - sobes.tech