PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] What is causing this unknown error in my code?

 May 13, 2022     append, arrays, swift, swiftui     No comments   

Issue

I am trying to make an app where whenever a certain button is clicked, the value of a score variable (whatever its value is at the time) is appended to an array. I made a NavigationLink that brings you to another view where it presents all the scores. However, whenever I click the NavigationLink to see the scores, it crashes. The error is "Thread 1: Fatal error: Index out of range".

Here is the code for the button:

Button(action: {
    gameTracker += 1
    counter += 1
    gameScores.append(scoreTracker)
            
    roundTracker = 1
    scoreTracker = 0
}

Here is the code for the view which is meant to show up after the NavigationLink is clicked:

struct scoreView: View {
    @Binding var scoreTracker: Int
    @Binding var gameTracker: Int
    @Binding var gameScores: [Any]
    @Binding var counter: Int
    var body: some View {
        Text("Scores: ")
        
    VStack {
        List {
            ForEach(0..<counter) {
                Text("Game \($0): \(String(describing: gameScores[counter])) ")
                }
            }
            
        }
    }
}

Does anyone have an idea on what could be wrong?


Solution

You can try this code, you should use $0 instead counter:

struct scoreView: View {
@Binding var scoreTracker: Int
@Binding var gameTracker: Int
@Binding var gameScores: [Any]
@Binding var counter: Int
var body: some View {
    Text("Scores: ")
    
VStack {
    List {
        ForEach(0..<counter) {
            Text("Game \($0): \(String(describing: gameScores[$0])) ") // <<: Here!
            }
        }
        
    }
    }
}


Answered By - swiftPunk
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing