Skip to content

/compare/swift/struct-vs-class

Swift struct vs class: value type or reference type?

The commands on this page have not been executed by our verification runner yet.updated
tool
Swift
compares
struct vs class

In Swift a struct is a value type: assigning it or passing it to a function copies the value, so each variable has its own independent data. A class is a reference type: assignments share one instance, and a change through one reference is visible through all of them. Apple's guidance is to use structures by default and choose a class when you need inheritance, shared mutable state with identity (===), deinitializers, or Objective-C interoperability.

Copy vs share

swift
struct PointS { var x = 0 }
final class PointC { var x = 0 }

var a = PointS(); var b = a     // b is a copy
b.x = 5
print(a.x, b.x)                 // 0 5

let c = PointC(); let d = c     // d refers to the same object
d.x = 5
print(c.x, d.x)                 // 5 5
print(c === d)                  // true: same instance

Note that c is a let constant and its property still changed: let fixes the reference for classes, but the whole value for structs.

Differences

structclass
TypeValue type (copied)Reference type (shared)
InheritanceNo (protocols only)Yes, single inheritance
Memberwise initializerGenerated automaticallyWrite init yourself
Mutating a let instanceNot allowedAllowed for var properties
Methods that change selfMust be marked mutatingNo keyword needed
Identity (===)NoYes
deinitNoYes
Memory managementNo reference counting for the value itselfARC; watch for retain cycles (weak, unowned)

Which one to use

  • struct: models and data (User, Settings, API responses), SwiftUI views and state values, anything you want to pass around without side effects. Arrays, dictionaries and strings in the standard library are structs too, with copy-on-write storage.
  • class: objects with a lifetime and identity (a network session, a cache, a view controller), types that must subclass a framework class (UIViewController, NSObject), or shared state observed by several parts of the app.

Sources