Learn Courses My Dashboard

Mutating vs @State

While I was developing the war card game app I decided to use a struct to represent a player and then in ContentView created two @State properties to represent the player and cpu. Within the Player struct I created a function named draw which would create the card and then update the stored card property with that value. When I did this I noticed that Xcode threw an error stating I couldn’t update the property and suggested to add the “mutating” keyword to my method declaration.

I looked at developer documentation for methods and it is in there as a way to update struct properties within a method. However, what’s the difference between this a @State? When should you use mutating vs @State?

From what I gather, @State would be used when the property is being used by a View and mutating is for non-view property updates?

I think we can use mutating for Functions and state for variables. I’m not 100% sure but I read it in somewhere .

Hi @jasonabullard

There are good articles in Medium created by Eniela P. Vela about Mutating variables and @State in Swift. I will link the articles for you.

  1. Mutating Variables in Swift
  2. @State in Swift/SwiftUI

Thanks for the articles. Those confirm what I thought that @State is for variables binding to a UI element, whereas mutating would be for a struct that is not a view.