Introducing mutating methods

Methods in structures cannot change the values of the instance without being marked as mutating. You can imagine a method in the Date structure that advances to the next day:

mutating func advance() { day += 1

}

The mutating keyword marks a method that changes a structure’s value. Since a structure is a value type, each time it’s passed around an app, the system copies it. If a method changes the value of one of the properties, then the original instance and the copied instance are no longer equivalent.

By marking a method as mutating, you’re telling the Swift compiler this method must not be called on constants. This is how Swift knows which methods to allow and which reject at compile time. If you call a mutating method on a constant struct, the compiler will flag it as an error that must be corrected before you can run your program.

The implementation above is a naive way of writing advance() because it doesn’t account for what happens at the end of a month. In a challenge at the end of this chapter, you’ll tackle the robust logic.

results matching ""

    No results matching ""