Sobes.tech
Middle

Mida tähendab, et väärtusetüüp (value type) kuulub viidetüübile (reference type)?

sobes.tech AI

Vastus AI-lt

Value type copies its value when assigned or passed to a function, while reference type passes a reference, meaning a pointer to the existing instance is copied.

Value Types:

  • Structures (struct)
  • Enums (enum)
  • Tuples (tuple)
  • Most primitive types (Int, String, Bool, Array, Dictionary, Set, etc.)
struct Point {
    var x: Int
    var y: Int
}

var p1 = Point(x: 1, y: 2)
var p2 = p1 // copies the value of p1 into p2
p2.x = 10

// p1.x is still 1, p2.x is 10
print("p1: \(p1.x)")
print("p2: \(p2.x)")

Reference Types:

  • Classes (class)
  • Functions (closures)
class Coordinate {
    var x: Int
    var y: Int

    init(x: Int, y: Int) {
        self.x = x
        self.y = y
    }
}

var c1 = Coordinate(x: 1, y: 2)
var c2 = c1 // c2 references the same instance as c1
c2.x = 10

// c1.x is also 10
print("c1: \(c1.x)")
print("c2: \(c2.x)")

Main differences:

Characteristic Value Type Reference Type
Assignment Copies the value Copies the reference (pointer)
Memory Allocated on the stack (for simple cases) Allocated on the heap
Sharing Each variable has its own copy Multiple variables can refer to the same instance
Mutability To modify, the copy must be modified Changes through one reference are visible to all

Both types are often used in iOS development. Knowing their differences helps choose the appropriate type for a specific task and avoid unwanted side effects, especially when working with mutable data.