Start learning free

LESSON 153 OF 349 · SWIFT ESSENTIALS

Structs vs classes: copy or share? in Swift

Lesson

Swift gives you two ways to bundle data together: struct and class. They look almost identical on the page:

struct PlayerStruct {
    var score = 0
}
class PlayerClass {
    var score = 0
}

The difference is what happens on assignment:

  • A struct is a value type: var b = a makes a full, independent COPY. Change b, and a doesn't care.
  • A class is a reference type: let b = a copies only a reference. Both names point at ONE shared object — change it through either name and both see it.

Same syntax, opposite behavior — and it decides whether a change in one corner of your program silently shows up in another.


The trap:

Because a struct copy is a real value of its own, mutating it through a let constant is forbidden. This looks harmless:

let copy = original   // original is a struct
copy.score = 100

...and the compiler refuses it:

trap.swift:6:6: error: cannot assign to property: 'copy' is a 'let' constant
4 | let original = Player()
5 | let copy = original
  |     `- note: change 'let' to 'var' to make it mutable
6 | copy.score = 100
  |      `- error: cannot assign to property: 'copy' is a 'let' constant

Do what the note says: declare the copy with var. The flip side surprises people just as much: a let constant holding a class instance DOES allow copy.score = 100 — only the reference is constant, not the object it points to.


Assignment
Follow the Coding Tutorial and see both behaviors with your own eyes:

  • define PlayerStruct (struct) and PlayerClass (class), each with var score = 0,
  • make structCopy from structOriginal, set the copy's score to 100, print both,
  • make classCopy from classOriginal, set its score to 100, print both.

The exact expected output is:

struct original = 0
struct copy = 100
class original = 100
class copy = 100

Hint
Only structCopy needs var — you mutate the struct value itself. The class bindings can all stay let, because you never change what they point at, only the object's property.


STEP 1 OF 14
    Ctrl + Enter to check

    Structs Vs Classes in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free