I have an empty array of structures. I want to initialize it before I try to display it. I probably did something stupid. In my view I put an init. I ran the debugger and stopped at the append. Down in the debug area it said I had 0 values. That did not change and later when I went to display the data I got the fatal error that the index was out of range. I know when I created the array the 0 element was out of range, but I went through the init code in the, apparently fruitless, hope it would get initialized before it ran.
On another note. I am probably doing it wrong and would not be adverse to changing my code. What I want is an array with 6 elements created when I start the application. The structure that makes up the array does not require an initializer.
The array is a State variable because I am going to change the values for elements in it and when I change them I want a redraw. I am not going to change the number of elements, just data in the existing elements.
Edit: I seem to remember that I can put stuff in the app file that will be available to all. I would not have a problem moving my data there, but it seemed simpler to have it in the view that used it.
Another edit: I changed the definition of the array to create the elements and it apparently worked. That's fine, but it still puzzles me why init did not work. Probably going to run across the iagain.
struct Player {
var name = ""
}
struct ContentView: View {
@State private var players: [Player] = []
init (){
for _ in 0...5 {
players.append(Player())
}
}
var body: some View {
HStack {
TextField ("Player 1", text: $players[0].name)
}
}
}