DevPrep

All topics › The Swift Language

let vs var for a struct — what changes with mutating methods?

Junior PRO

The idea

A struct is a value type, and the constness of let applies to the whole value: you cannot assign a new value, cannot change any property (even a var one), cannot call a mutating method. mutating means the method may change self — up to replacing it entirely with self = Counter() — so on a let the compiler forbids it.

struct Counter {
    var value = 0
    mutating func increment() { value += 1 }
}

let fixed = Counter()
// fixed.value = 1      // error: 'fixed' is a 'let' constant
// fixed.increment()    // error: cannot use mutating member on immutable value
var counter = Counter()
counter.increment()      // ok

final class Box { var value = 0 }
let box = Box()
box.value = 1            // ok: the reference is constant, not the object

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store