Updated for Xcode 12.5
It’s possible to modify the properties of a struct, but only if that struct is created as a variable. Of course, inside your struct there’s no way of telling whether you’ll be working with a variable struct or a constant struct, so Swift has a simple solution: any time a struct’s method tries to change any properties, you must mark it as mutating
.
You don’t need to do anything else other than mark the method as mutating
, but doing that gives Swift enough information to stop that method from being used with constant struct instances.
There are two important details you’ll find useful:
mutating
will stop the method from being called on constant structs, even if the method itself doesn’t actually change any properties. If you say it changes stuff, Swift believes you!SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.