In Swift, why does a protocol mark a method requirement `mutating`, and how do struct and class conformers satisfy it?
answer
- value types need permission to change self
- classes never write the keyword
- a weaker witness is fine
- let through the protocol type
basics
~20 sMarking a requirement mutating lets structs and enums satisfy it with a method that changes self. Classes implement it without the keyword. A non-mutating implementation also satisfies it, but a mutating one cannot satisfy a non-mutating requirement.
solid answer
~40 sFor a struct or enum, a method that changes `self` must be `mutating`, so a protocol intended to modify its conformers marks the requirement `mutating func store(_:forKey:)`; without it, a struct could not conform. A class writes the method without the keyword, since writing `mutating` in a class is an error ("'mutating' is not valid on instance methods in classes"). The matching is one-directional: a plain method satisfies a `mutating` requirement, but a `mutating` method cannot satisfy a non-mutating requirement ("candidate is marked 'mutating' but protocol does not allow it"). The cost is at the call site: through `let boxed: any Cache` or a generic parameter, a `mutating` requirement cannot be called, even when the value is a class, because the compiler must assume a value type.
code
swift · 30 linesprotocol Cache {
func value(forKey key: String) -> String?
mutating func store(_ value: String, forKey key: String)
}
struct InMemoryCache: Cache {
private var storage: [String: String] = [:]
func value(forKey key: String) -> String? { storage[key] }
mutating func store(_ value: String, forKey key: String) {
storage[key] = value
}
}
final class DiskCache: Cache {
private var index: [String: String] = [:]
func value(forKey key: String) -> String? { index[key] }
func store(_ value: String, forKey key: String) { // no 'mutating' in a class
index[key] = value
}
}
func warmUp<C: Cache>(_ cache: inout C) {
cache.store("v1", forKey: "config")
}
var memory = InMemoryCache()
warmUp(&memory)
var disk = DiskCache()
warmUp(&disk)
print(memory.value(forKey: "config") ?? "-", disk.value(forKey: "config") ?? "-")go deeper
Recall that structs and enums need mutating to change self, so protocols mark such requirements mutating, and classes implement them without the keyword.
Explain the one-way matching: a plain method satisfies a mutating requirement, but a mutating method fails a non-mutating one, and show the exact compiler note for that failure.
Diagnose the call-site errors: a let existential or a generic parameter cannot call a mutating requirement even for a class, and fix them with inout, a local var or a class-only protocol.
Treat mutating as a contract cost on every caller; reserve it for requirements value types must implement by changing themselves, and prefer class-only protocols where conformers are always objects.
## Why `mutating` exists on requirements In Swift, **structures and enumerations are value types**. Their instance methods cannot modify `self` or its stored properties unless the method is marked **`mutating`**; a mutating method may even assign a whole new value to `self`. Classes are reference types: their methods can always change the object's properties, and the keyword does not apply to them. A protocol does not know which kind of type will adopt it. If a requirement is meant to change the conformer, such as storing a value in a cache, the protocol marks it `mutating`: ```swift protocol Cache { func value(forKey key: String) -> String? mutating func store(_ value: String, forKey key: String) } ``` That marking is what allows a struct like `InMemoryCache` to conform with a `mutating func store`. Leave it off, and no struct can satisfy the requirement with a method that writes to its storage. ## How each kind of conformer satisfies it | Conformer | Requirement is `mutating` | Requirement is not `mutating` | |---|---|---| | struct or enum, `mutating func` | satisfies it | rejected: "candidate is marked 'mutating' but protocol does not allow it" | | struct or enum, plain `func` | satisfies it | satisfies it | | class, plain `func` | satisfies it | satisfies it | | class, `mutating func` | error: "'mutating' is not valid on instance methods in classes" | same error | The rule behind the table: a requirement states the **most** a conformer may do. A `mutating` requirement permits mutation but does not demand it, so a non-mutating implementation is acceptable. A non-mutating requirement promises callers they can call it on an immutable value, so an implementation that needs to mutate breaks the promise. ## What callers pay Because a `mutating` requirement might be implemented by a value type, calling it through the protocol needs a mutable value: - `let boxed: any Cache = DiskCache()` followed by `boxed.store("b", forKey: "k")` fails with "cannot use mutating member on immutable value: 'boxed' is a 'let' constant", **even though `DiskCache` is a class**. The compiler reasons about the protocol type, not the dynamic type. - Inside `func fill<C: Cache>(_ c: C)`, calling `c.store(...)` fails the same way, because parameters are constants. Take the parameter `inout C`, or copy it into a local `var`. - On the concrete class type, `let disk = DiskCache(); disk.store(...)` compiles, since the class's method is not mutating. Two consequences follow: 1. Mark a requirement `mutating` only when a value-type conformer genuinely needs to change itself. Otherwise you push `var` and `inout` onto every caller for nothing. 2. A protocol that will only ever be adopted by classes can be restricted to classes; then `mutating` is not allowed on its requirements at all ("'mutating' is not valid on instance methods in class-bound protocols"), and callers can use `let`. ## Common mistakes in review - Marking every requirement `mutating` "just in case", which forces `var` on callers that only read. - Leaving `mutating` off a requirement that a struct must implement by writing to its storage, then working around it with a class wrapper. - Expecting a `let` of the protocol type to behave like a class reference because today's only conformer is a class. - Copying a struct conformer into a local `var` inside a generic function and wondering why the caller's value did not change. ## Interview framing State the purpose (value-type conformers), the class rule (no keyword), the one-way matching, and the call-site cost through `any` or a generic parameter. Candidates who can explain why `let boxed: any Cache` holding a class still cannot call `store` show they understand that Swift type-checks against the protocol, not the object.
- Your generic function `func fill<C: Cache>(_ c: C)` cannot call the mutating `store(_:forKey:)`. What are the fixes?Take the parameter as `inout C` and call it with `&cache`, so mutations reach the caller's value; or copy into a local `var` when the change should stay local, which for a struct conformer means the caller sees nothing. If every conformer is a class, restricting the protocol to classes removes `mutating` and the problem.
- Does a class conformer's implementation ever reassign `self` like a struct's mutating method can?No. A class method cannot assign to `self`; it changes the object's properties in place. A struct's mutating method may replace `self` entirely. That is why a mutating requirement called on a struct can swap the whole value, while the same call on a class mutates the shared object every reference sees.
- A class must also mark the method mutating to satisfy a mutating requirement.
- A mutating struct method can satisfy a non-mutating protocol requirement.
- A let holding a class can call any mutating requirement through the protocol type.
- A mutating requirement forces every conformer's implementation to mutate.
- Adding mutating to requirements is harmless for callers.