2

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])}
                
            }
              
    }
}
6
  • Why not replace groupsize with nameArray.count? Commented May 10, 2021 at 19:26
  • This is since the number of values I want to store depends on the groupsize variable that comes from the previous view. Commented May 10, 2021 at 19:32
  • 2
    groupsize > nameArray.count which is the problem here Commented May 10, 2021 at 19:40
  • Do ForEach(0 ..< groupsize - 1), but as @George_E mentioned, this might not be a good design choice Commented May 10, 2021 at 19:52
  • @aheze This doesn't work Commented May 10, 2021 at 20:25

1 Answer 1

3

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)
            }
        })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.