Explain the difference between 'struct' and 'class' in Swift.

Instruction: Provide a detailed comparison, including the concept of value types vs. reference types.

Context: This question assesses the candidate's understanding of fundamental Swift programming concepts, specifically around data structures and memory management. It tests their knowledge of 'struct' and 'class', including the implications of using each in terms of value types and reference types, inheritance, and mutability.

Updated

Official answer

A struct is a value type; an ordinary copyable struct is copied on assignment or argument passing. A class is a reference type: assigning its reference gives another name for the same instance. Both support properties, methods, initializers, extensions and protocol conformance; class inheritance adds shared implementation and identity when those are needed.

Mutability is separate from that distinction. A var struct can change its var properties, and a mutating method can change its value. A let struct cannot have its stored properties reassigned. A let class reference cannot be rebound, but its object's var properties can still change. This complete Swift example demonstrates both:

struct Point { var x: Int }
final class Box {
    var x: Int
    init(_ x: Int) { self.x = x }
}

var first = Point(x: 1)
var second = first
second.x = 2
assert(first.x == 1 && second.x == 2)

let original = Box(1)
let alias = original
alias.x = 2
assert(original === alias && original.x == 2)

struct Container { let box: Box }
let left = Container(box: original)
let right = left
right.box.x = 3
assert(left.box.x == 3)

The last case matters: copying a struct containing a class reference does not deep-copy the referenced object. Value types are therefore not automatically deeply immutable or safe for arbitrary concurrent mutation. Standard collections can use copy-on-write while preserving their value behavior; do not infer a universal stack-versus-heap allocation rule.

I would use small values for independent model data and classes when identity, shared lifetime or framework inheritance is required. ARC manages class references, so strong cycles need attention. Classes support deinit; modern noncopyable structs/enums can also define one, so “structs never have deinitializers” is too broad. Choose based on semantics, then measure any performance concern.

Swift value and reference types, ARC and closure cycles, Noncopyable types and deinit

Related Questions