Let's start with some code segments
struct DigitS {
var number = 42
init(_ n: Int) {
self.number = n
}
mutating func replace() {
self = DigitS(12) // mutating
}
}
class DigitC {
var number = 42
init(_ n: Int) {
self.number = n
}
func replace() {
self = DigitC(12) //#Cannot assign to value: "self" is immutable
}
}
For a very long time, I was very confused about the meaning of mutable, modifiable. Here are some of my understandings so far, would be nice if you can point out all errors it may have
Mutating function in the structure type above does not "mutates" the instance, it will replace the old value of the variable by a totally new one
Mutating means: the action like assignment, initialization or mutating function does not modifies the current value but a triggers a replacement
A class typed variable's value is immutable, but you can modify/change the current value (this is the reason the compiler gives out the warning, please see the comments with #)
The setter observer, can only be called if the type is a value type, because setter tells if the variable has been mutated/replaced (please see code below)
struct Digit { var number = 12 } var b = Digit() { didSet{ print("number is set") } } b.number = 22 // observer is called class Digit { var number = 12 } var b = Digit() { didSet{ print("number is set") } } b.number = 22 // observer is not called
Thanks for your time and help