1 minute read

The Difference Between Structs and Classes in Swift

Swift gives developers two main ways to model data: structs and classes. They can both contain properties, methods, initialisers, and protocols, so the choice may seem cosmetic when you are starting with iOS development. It is not. Their different ownership and copying rules affect correctness, memory use, UIKit design, and how easily a project can grow.

For a junior developer building an app after school in Australia, the distinction appears quickly. A timetable, café menu, or tram route may work well as a value type, while a shared session, image cache, or view controller usually needs reference behaviour. Understanding the model behind each type is more useful than memorising a simple rule such as “struct for small data, class for large data”.

Structs Represent Independent Values

A struct is a value type. When you assign a struct to another variable or pass it into a function, Swift treats the result as a separate value. Changing one variable does not normally change the other.

struct Trip {
    var destination: String
    var minutes: Int
}

var morningTrip = Trip(destination: "Melbourne", minutes: 25)
var copiedTrip = morningTrip

copiedTrip.minutes = 35

print(morningTrip.minutes) // 25
print(copiedTrip.minutes)  // 35

This behaviour is useful because each value has a clear meaning on its own. A Trip, UserProfile, TemperatureReading, or Product can be passed between views without another part of the app unexpectedly modifying it. Swift’s standard library relies heavily on structs, including String, Array, Dictionary, and Date.

Structs also receive several conveniences from the language. Swift can synthesise a memberwise initialiser, and structs can conform to protocols without needing inheritance. Their predictable ownership makes them a natural choice for data transferred between SwiftUI views, model layers, and networking code.

Classes Share References

A class is a reference type. Assigning a class instance to another variable copies a reference to the same object. Both variables can therefore point to one piece of mutable state.

final class Download {
    var progress = 0
}

let first = Download()
let second = first

second.progress = 50

print(first.progress) // 50

This is valuable when several parts of an application must observe or update the same object. A networking coordinator, authentication manager, database controller, or image cache often has a single meaningful identity. Creating independent copies could produce conflicting state.

The trade-off is that shared references make changes less visible. A function may receive a class instance and alter it without returning anything, which can make debugging harder. When a class is intended to have one identity and no subclass should extend it, marking it final communicates that design clearly and can avoid unnecessary dynamic dispatch.

Value Semantics Protect Data

Value semantics are about independent meaning, not simply about stack versus heap memory. Swift is free to optimise how values are stored. For example, arrays use copy-on-write: assigning an array is inexpensive at first, and actual storage is copied only when one version needs a change.

var firstStops = ["Central", "Town Hall"]
var secondStops = firstStops

secondStops.append("Wynyard")

print(firstStops)  // ["Central", "Town Hall"]
print(secondStops) // ["Central", "Town Hall", "Wynyard"]

This makes value types a strong fit for state that should be replaced rather than secretly mutated. A screen displaying a Sydney ferry timetable can receive a new timetable value after a refresh, while the previous value remains safe for rendering or testing.

There is an important detail: a struct can contain a reference type. A struct containing a class property is still copied as a value, but the nested class object may remain shared. Similarly, an Array of class instances copies the array container while preserving references to its objects. Value semantics are therefore a design promise that may require careful attention to every stored property.

Identity Makes Classes Different

Classes support identity, inheritance, and deinitialisation. Two separate instances can hold exactly the same data but still be different objects. You can test identity with the === operator.

final class Account {
    let email: String

    init(email: String) {
        self.email = email
    }
}

let accountA = Account(email: "dev@example.com")
let accountB = Account(email: "dev@example.com")

print(accountA == accountB) // No automatic equality
print(accountA === accountB) // false

A class is appropriate when “which object is this?” matters. A UIViewController, UIView, URLSession delegate, or observable store has a lifecycle and identity beyond its stored properties. UIKit itself is built around reference types, so a button or view controller should not be copied as if it were a simple piece of data.

Classes use automatic reference counting, or ARC. Swift releases an object when its strong references disappear. Strong reference cycles can prevent that from happening, especially when closures capture self. Use weak or unowned only when the ownership relationship supports it, and understand the lifetime before choosing either keyword.

Copying Is Not the Same as Cloning

The word “copy” can be misleading in Swift. Assigning a struct creates independent value behaviour, but assigning a class creates another reference to the same instance. If an actual independent class object is required, you must design and implement a copying operation yourself.

For example, a class might provide a method that creates a new instance from its current properties. However, that method must decide whether nested objects are copied as well. A shallow copy duplicates the outer object but shares inner references; a deep copy creates independent nested data. Neither is automatically correct for every app.

let also behaves differently. A let struct cannot have its stored properties changed, while a let class reference cannot point to a different object but can still access mutable properties on that object.

let settings = UserSettings()
settings.theme = .dark // Allowed if theme is var

Understanding this distinction prevents confusing bugs in projects such as a school planner or a local-market shopping app. A constant reference is not the same as an immutable object.

Choosing Types In Real iOS Projects

Start with a struct when the type describes data, has no meaningful identity, and should be safe to pass around. API response models, form state, coordinates, settings, and view configuration are common examples. A struct also works well when replacing the whole value is clearer than modifying a shared object.

Choose a class when the instance has a lifecycle, must be shared, needs inheritance, or represents an external resource. View controllers, delegates, coordinators, cache managers, and long-lived services commonly belong here. Protocols can help reduce coupling, allowing a class to provide behaviour while other code depends on an abstraction.

For a junior developer working on an app aimed at people in Brisbane, Perth, or regional Queensland, this choice can influence reliability on slower connections and older devices. Immutable-looking value models make loading and retry states easier to test, while a shared networking service can prevent duplicate requests. Reading concise Swift learning notes can supplement Apple’s documentation, but experiments in a small Xcode project will reveal ownership rules most clearly.

Performance Depends On Design

Structs are not automatically faster, and classes are not automatically wasteful. A large struct passed through an app may trigger copying costs, although Swift often optimises them. A class may avoid copying its storage, but it introduces heap allocation, reference counting, and possible contention around shared mutable state.

The right question is whether the data benefits from independent values or shared identity. A value type can be efficient and thread-friendly, particularly when used with structured concurrency. A reference type can be the better option for a resource that should have one owner or one coordinated lifecycle. Measure with Instruments when performance matters rather than relying on assumptions.

Concurrency makes the distinction even more important. Immutable structs are easier to send between tasks safely. Mutable classes require stronger discipline, such as actor isolation or main-actor access. UIKit updates belong on the main actor, which is especially relevant when a class-based view model receives results from a background network request.

Practical Rules For Swift Projects

Use these recommendations as a starting point rather than an inflexible law:

  • Choose a struct for independent data with no meaningful identity.
  • Choose a class for shared state, lifecycle management, or inheritance.
  • Prefer immutable properties and methods where mutation is unnecessary.
  • Mark classes final when subclassing is not part of the design.
  • Watch for reference cycles in closures, delegates, and observable objects.
  • Test assignments and mutations with small examples before building a larger feature.
  • Use Instruments and concurrency diagnostics when performance or thread safety is uncertain.

A useful exercise is to model one feature twice. Build a timetable as a struct, pass it between functions, and observe independent copies. Then create a class-based session object, share it across two components, and watch how a mutation becomes visible in both places. This contrast turns an abstract language rule into something you can recognise during debugging.

The practical takeaway is simple: use structs when a value should stand alone, and classes when an object needs shared identity or a managed lifetime. Make that decision deliberately, then let protocols, immutability, testing, and profiling shape the rest of the design.

Updated: