Sobes.tech
Junior

What is the difference between structures and classes in Swift?

sobes.tech AI

Answer from AI

Main differences:

  • Value Type vs. Reference Type: Structures are value types, classes are reference types. When assigning a structure or passing it to a function, the value is copied. When assigning a class or passing it to a function, a reference to the memory block is copied.
  • Inheritance: Structures do not support inheritance. Classes support inheritance, allowing the creation of object hierarchies.
  • Deinitializers: Structures do not have deinitializers. Classes can have a deinitializer (deinit) to free resources.
  • Identity Equality: For structures, all their property values are compared (by default using ==). For classes, == by default compares references (identity).
  • Performance: Structures are generally more efficient when working with small amounts of data, as they do not use dynamic memory allocation on the heap and do not have reference counting overhead (ARC).
Criterion Structure (Struct) Class (Class)
Type Value (Value Type) Reference (Reference Type)
Inheritance No Yes
Deinitializers No Yes (deinit)
Identity Equality Compares property values Compares references
Location Usually stack (for local variables) Heap
ARC No Yes

The choice between a structure and a class depends on the needs. Structures are well-suited for modeling data where value passing is important (e.g., coordinates, size). Classes are used when inheritance, shared mutable references to an object, or resource lifecycle management are required.

// Structure example
struct Point {
    var x: Double
    var y: Double
}

var p1 = Point(x: 0.0, y: 0.0)
var p2 = p1 // p2 is a copy of p1
p2.x = 5.0

// p1.x remains 0.0
print("p1.x: \(p1.x), p2.x: \(p2.x)")

// Class example
class Circle {
    var radius: Double
    init(radius: Double) {
        self.radius = radius
    }
    deinit {
        print("Circle instance is being deinitialized.")
    }
}

var c1 = Circle(radius: 1.0)
var c2 = c1 // c2 references the same instance as c1
c2.radius = 10.0

// c1.radius also becomes 10.0
print("c1.radius: \(c1.radius), c2.radius: \(c2.radius)")

// Identity comparison
if c1 === c2 { // compares references
    print("c1 and c2 refer to the same Circle instance.")
} else {
     print("c1 and c2 do not refer to the same Circle instance.")
}

// Value comparison (for structures)
let p3 = Point(x: 0.0, y: 0.0)
if p1 == p3 { // compares all property values
    print("p1 and p3 have the same value.")
} else {
    print("p1 and p3 do not have the same value.")
}
What is the difference between structures and classes… - sobes.tech