I have a struct called Answer
which holds a couple properties, one of which is value: String?
. In my SwiftUI app, I ask the user to enter their answer into a textfield from which I'd then like to save the result in the answer object – something like this:
struct Answer {
var id: Int
var value: String?
}
var answers: [Answer]!
var body: some View {
ForEach(answers, id: \.id) { answer in
TextField("Answer \(id.string) here", text: $answer.value)
}
}
This doesn't work unfortunately. Error message:
Cannot find '$answer' in scope
What I'd not like to do is create a separate @State
variable for each answer, because I'm asking a whole bunch of questions and thus want to save a lot of answers (which I get from an API, so I don't know which / how many answers there will be).
How do I implement such a thing?