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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.