Mutating protocol extension function forces class to be declared with var

And there's an interesting related discussion here.

That is:

protocol HasMutatingFunction {
    mutating func mutatingProtocolFunction()
    init()
}

extension HasMutatingFunction {
    mutating func mutatingExtensionFunction() {
        mutatingProtocolFunction()
        mutatingProtocolFunction()
        self = Self.init() // <--- Note that this is OK here.
    }
}

class C : HasMutatingFunction {
    var count: Int = 0
    required init() { }
    func increment() { count += 1 }
    func mutatingProtocolFunction() {
        count += 5
        // self = Self.init() // <--- But not here.
    }
}
1 Like