AnyCompiler

Mutating Methods

Because a struct is a value type, an instance method on a struct treats self as read-only by default — even a method defined inside the struct itself can't change one of its own properties unless the method is explicitly marked mutating. This is a genuinely Swift-specific rule: no class-based language on this site needs it, since every class there is already a reference type where methods can freely change its fields.

What the real compiler error looks like

Leaving out mutating on a struct method that tries to change a property isn't a warning — it's a compile error. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:

struct Counter {
    var count: Int = 0
    func increment() {
        count += 1
    }
}
var c = Counter()
c.increment()
print(c.count)
Output
Main.swift:5:15: error: left side of mutating operator isn't mutable: 'self' is immutable
        count += 1
        ~~~~~ ^
Main.swift:4:5: note: mark method 'mutating' to make 'self' mutable
    func increment() {
    ^
    mutating 

Adding mutating before func fixes it immediately — it tells the compiler this specific method is allowed to replace self's properties, and that calling it requires a var instance (a let Counter couldn't call it at all).

struct Counter {
    var count: Int = 0
    mutating func increment() {
        count += 1
    }
}
var c = Counter()
c.increment()
c.increment()
print(c.count)
Output
2

Next: properties — computed properties and property observers, which run code automatically on read or write.

Practice exercise

Define a struct named Counter with var count: Int = 0 and a mutating method increment() that adds 1 to count. Create var c = Counter(), call c.increment() three times, then print c.count.