Mutating Methods
If a method inside a struct will alter a property of the struct itself, it must be declared as mutating
. This means that if the struct has some property that belongs to the struct itself (not a local variable inside a method) and you try to set that property, you will get an error unless you mark that method as mutating
. Here’s a struct that will throw an error:
struct someStruct { var property1 = "Hi there" func method1() { property1 = "Hello there" // property1 belongs to the class itself so we can't change this with making some changes } // ERROR: cannot assign to 'property1' in 'self'}
The fix for this error is simple. Just add the word mutating
in front of the
Get Learning Swift™ Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.