Adding textfield input to array during forEach in SwiftUI

Viewed 949

I'm new to Swift / SwiftUI and trying to store the textfield value in an array during a foreach. However I'm encountering a Thread 1: Fatal error: Index out of range message. Should the storing the value happen outside the view(View Model) or can it be done inside a View??

struct OrderView: View {
    
    @Binding var groupsize: Int
    
    @State var nameArray = [String]()
    
    var body: some View {
            
            VStack {          
                
                ForEach(0 ..< groupsize) { index in
                    TextField("Insert name", text: $nameArray[index])}
                
            }
              
    }
}
1 Answers

taking all the good advice of the comments, you could try something like this:

struct OrderView: View {
    @Binding var groupsize: Int
    @State var nameArray = [String]()
    
    var body: some View {
        VStack {
            if nameArray.count > 0 {
                ForEach(0 ..< groupsize) { index in
                    TextField("Insert name", text: $nameArray[index])}
            }
        }.onAppear(perform: {
            if groupsize > 0 {
                nameArray = [String](repeating: "", count: groupsize)
            }
        })
    }
}
Related