Cannot assign to property: 'self' is immutable?

Making protocol members mutating makes it a bit more inconvenient to work with classes (which don't directly support mutating members) and as a corollary you can have some surprising behavior:

protocol P {
    init()
}

extension P {
    mutating func f() {
        self = .init()
    }
}

final class C: P {}

let c1 = C()
c1.f() // error: cannot use mutating member, 'c1' is a 'let' constant

let c2_let = C()
var c2_var = c2_let
c2_var.f()

c2_let === c2_var // false, the instance has changed!
3 Likes