Swift Tutorial

Structs vs. Classes

Value types vs Reference types in the Swift language

Value Types vs. Reference Types

This is the most important architectural concept in Swift.
  1. Structs (Value Types): When you copy a struct, you create a brand new copy of the data. Changes to the copy don't affect the original.
  2. Classes (Reference Types): When you copy a class, you create a new reference to the same data in memory. Changes to one affect all others.
swift
struct Point { var x: Int }
class User { var name: String; init(n: String) { name = n } }

When to use which?

FeatureStructClass
TypeValue TypeReference Type
MemoryStack (Fast)Heap (Slower)
CopyingCopy dataCopy reference
InheritanceNoYes
MutabilityBased on var / letCan change internal data even if let

Mutating Methods

Wait! In a struct, if you want to change one of its properties inside a method, you must mark that method as mutating.
swift
struct Counter {
    var count = 0
    mutating func increment() {
        count += 1
    }
}

The Swift Philosophy: "Structs First"

Apple recommends using Structs by default for almost everything. They are faster, safer, and easier to reason about because you don't have to worry about "hidden" changes from other parts of your code.
Only use Classes when you specifically need Inheritance or Identity (e.g., a Database connection that must be shared).

Summary

TermDescription
StructValue type (The default choice in Swift)
ClassReference type (Use for shared identity)
MemberwiseStructs get a free constructor automatically
DeinitClasses can run code right before they are destroyed
Identity=== - Checking if two variables point to the exact same object
Best ForModeling data (Structs) or shared services (Classes)
LogicFavor "Immutability" and "Values"
SafetyStructs prevent "Race Conditions" in multi-threaded code
ModernSwiftUI is built entirely on Structs
StandardUse PascalCase for both names
IdentityStructs are compared by value; Classes by memory address