How to Choose Between Struct and Class in Swift

Written by

in

Quick answer: Default to struct in Swift for data models and everyday types because value semantics prevent unintended shared state and make concurrent code safer. Use class only when you need reference identity, a deinit lifecycle tied to external resources, or shared mutable state across your app.

Why this happens

If you are coming to Swift from Java, C#, or Objective-C, struct can look like a stripped-down class with fewer features. In those languages, classes are the default building block for almost everything, and structs are either absent or reserved for tiny primitives.

Swift flips that model. A struct is a value type, meaning each assignment or function call passes an independent copy of the data. A class is a reference type, meaning multiple variables can point to the exact same instance in memory.

Choosing the wrong one creates subtle bugs. If you use a class for simple data, changing a property in one view or background task can silently mutate data held somewhere else. Conversely, forcing a struct where shared identity is required leads to awkward workarounds and out-of-sync state.

How to fix it

1. Default to struct for data models and state

For most custom types—such as user profiles, coordinates, API responses, and SwiftUI views—start with a struct. Because structs are copied on assignment, you do not have to worry about another part of your codebase mutating your data underneath you.

struct Point {
    var x: Double
    var y: Double
}

var origin = Point(x: 0, y: 0)
var moved = origin
moved.x = 10

// origin.x is still 0; moved.x is 10

Value semantics also reduce the risk of memory leaks caused by retain cycles and eliminate many race conditions when passing data across threads. In Swift, Array, Dictionary, and String are all structs for this exact reason.

2. Replace class inheritance with protocols and extensions

One common reason developers reach for class is inheritance. However, single-inheritance hierarchies often grow into bloated base classes that bundle unrelated responsibilities.

Instead of building a deep class hierarchy, define small protocol types and add shared behavior through protocol extensions. Both structs and classes can conform to protocols, and a struct can conform to as many protocols as it needs.

protocol Drawable {
    func draw()
}

extension Drawable {
    func describe() {
        print("Rendering a drawable shape")
    }
}

struct Circle: Drawable {
    var radius: Double

    func draw() {
        print("Circle with radius \(radius)")
    }
}

This protocol-oriented approach keeps your types decoupled, easier to test, and free from fragile superclass dependencies.

3. Use class when identity or external lifecycle matters

A struct is not always the right tool. Switch to a class when copying an instance does not make sense or when the object’s lifetime is tied to an external resource.

Common cases where class is the better choice include:

  • Shared identity: Two parts of your app must observe and mutate the exact same instance, such as a window controller or a shared network session.
  • Resource cleanup: You need a deinit method to close a file handle, invalidate a timer, or delete temporary files when the instance is deallocated.
  • Write-only conduits: The type acts as a sink to external state, similar to CGContext.
  • Objective-C interoperability: You need to subclass NSObject or work with legacy Apple frameworks that require reference types.
import Foundation

final class TemporaryFile {
    let url: URL

    init(url: URL) {
        self.url = url
    }

    deinit {
        try? FileManager.default.removeItem(at: url)
    }
}

Notice the final keyword. Marking a class final prevents accidental subclassing and lets the Swift compiler optimize method dispatch.

4. Watch out for closure captures and performance assumptions

Even when you use a struct, closures capture variables by reference by default. If a closure captures a mutable struct and runs later, it will read the latest mutated value unless you explicitly add a capture list.

struct Counter {
    var count = 0
}

var counter = Counter()
let logSnapshot = { [counter] in
    print(counter.count)
}

counter.count = 5
logSnapshot() // Prints 0 because [counter] captured a copy

On performance, structs are often faster because small value types can live on the stack and avoid heap allocation and reference-counting overhead. That said, a very large struct with many reference-type properties (like multiple arrays or classes inside it) still incurs retain/release traffic when copied. If performance is critical, profile your actual workload in Instruments rather than guessing.

How to prevent it

  • Start every new data type as a struct or enum, and only convert it to a class when you hit a concrete need for shared identity or deinit.
  • Keep structs focused and avoid stuffing dozens of reference-type properties into a single value type.
  • Use protocol composition and protocol extensions instead of creating shared superclasses.
  • Mark classes final unless you specifically design them for inheritance.
  • Use capture lists ([myStruct]) in escaping closures when you want a snapshot of a value type at creation time.

FAQ

Do structs copy all their data immediately on assignment?

For simple structs, Swift copies the value on assignment. Standard library collections like Array and Dictionary use copy-on-write, which means they share underlying storage until one copy is actually modified.

Can a struct contain a class property, or vice versa?

Yes. A class can hold struct properties without any issue. A struct can also hold a class property, though all copies of that struct will share a reference to the same class instance, which breaks pure value semantics.

Should SwiftUI view models be structs or classes?

SwiftUI View types are always structs because SwiftUI recreates them frequently to diff the UI. Observable view models that hold long-lived shared state across view updates are typically classes.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.