Var set to struct really replaced when modified?

37 Views Asked by At

Happy Holidays!

I got stymied on p.147 of Neuberg's "iOS 10 Programming Fundamentals". His claim is that "when you apparently mutate an instance of a value type, you are actually replacing that instance with a different instance."

Question: If this is true then why don't I see a new instance being initialized??

///////////////////// Slight modification from page 147 in Neuberg, 2016 edition
struct Digit {
    var number : Int
    init(_ n:Int) {
        self.number = n
        print("number was set in the initializer to: \(n)")
    }
}
var d : Digit = Digit(123) {
    didSet {   
        print("didSet detected old: \(oldValue.number) to new: \(d.number)")
    }
}
d.number = 42
d.number = 56

Prints--
number was set in the initializer to: 123
change in didSet detected from: 123 to 42
change in didSet detected from: 42 to 56

But I don't see any more, "number was set..."

1

There are 1 best solutions below

2
On BEST ANSWER

Replacing does not mean calling init again.

It conceptually means that you are copying the data, modifying (or mutating) the data (as to modify number), and replacing your original data with the modified data.

I haven't read this book, but I believe this point was raised to make clear the distinction between reference types and value types. Value types are passed by copying, reference types are passed by referencing (i.e. using pointers).