@State resetting my array

Been trying to use a ForEach loop to display the players cards from an array of data. When I add @State it resets to an empty array.

I’ve tried a bunch of different ways to write the code over the past three days. Been referencing other apps made with Chris and I can’t figure out what im doing wrong. Any input is helpful!

**I know the cards above are named differently, im using two sets of image data



The reason the array resets is you declared it inside the body property of the view instead of inside the view struct.

struct GameView: View {
  
  var body: some View {
    @State var playerCards = [Card]()
    // Rest of code omitted
}

You need to declare the array outside of the body, such as the following:

struct GameView: View {
  @State var playerCards = [Card]()

  var body: some View {
    // Body code here
}

It’s usually a bad idea to declare variables in the body of a SwiftUI view.

For future reference, post your code as text instead of screenshots. Text in screenshots is more difficult to read and can’t be copied and pasted.

Thanks really appreciate the that. Getting different code to work together feels like jumping through hoops in the dark.

Ill paste any code from now on, thanks again.

Just to add to the suggestion from SwiftDevJournal above, when you copy and paste in your code block, select that block and tap on the Quotes you see in the menu bar above the editing window, ie, as per this screenshot.

Alternatively just type 3 back-ticks ``` on a new line then hit return and paste your code in and then on the next line after the code you have pasted in type the same 3 back-ticks

So it would be something like this

```
Your code goes here
```

The backticks will not show up since it’s a formatting directive.

The back-tick character is on the same key as the tilde character. It may be in a different position depending on UK or US keyboard layout.

Hmmm, methinks I need to clean my keyboard.

1 Like

Ooooops. Correction with regard to the screenshot. It should be the </> button.