First of all, thank you for the great book, Swift Apprentice.
In Swift Apprentice 5th edition, I’ve read the following sentences:
“In Swift, an instance of a structure is an immutable value whereas an instance of a class is a mutable object.” (p. 311)
“As you’ve read before, instances of classes are mutable objects whereas instances of structures are immutable values.” (p. 320)
"If you had tried this with a struct, you’d have wound up with a compiler error, because structures are immutable. Remember, when you change the value of a struct, instead of modifying the value, you’re making a new value. The keyword mutating marks methods that replace the current value with a new one. With classes, this keyword is not used because the instance itself is mutable.” p. 322
I can not entirely understand the concept that “structs are immutable values”. When we declare a struct as a variable and when we declare the properties of the struct as variables, are we not able to mutate that instance of the struct? Then, how come that struct instance is an “immutable value”?
struct Car {
var color: String
}
var myCar = Car(color: "Red")
myCar.color // Red
myCar.color = "Green"
myCar.color // Green
In the code above, is not myCar
instance of the Car
struct mutable?
And when we declare a mutating
method in the struct, we can again change the Struct instance. Isn’t it mutable in that case?
“Remember, when you change the value of a struct, instead of modifying the value, you’re making a new value.”
As far as I can understand, “value” means the Struct’s instance here. When we create a Struct instance, we create a “value” (not a reference). My guess is, when we change that instance, we create another “instance” or “value” behind the scenes, am I right? Can you please convey this sentence in a more easy-to-understand way for beginners?
I hope you can clarify these for me, and maybe in the further editions of the book if you think some clarification might be useful for some readers.
Thank you!