I have dictionary that saves a questions as keys and answers as values ,I want change the answers using TextField each question to different answer and save them using UserDefaults . I tried different ways but I had some issues , like all the values of the dictionary would be saved to the same sting , or..it would show an error index out of range when I try to access dictionary.values.sorted()[Int].
1- created questions array
struct Questions :ObservableObject{
@Published var questions = [ “Q1” , “Q2” , “Q3” ]
}
2- here's the list of questions(I want the answers to be shown below the question)
struct FavoritesQuestionsListView:View {
@ObservedObject var questions = Questions()
@ObservedObject var dictionary = Dictionary()
@State var isPresented: Bool = false
var body: some View {
VStack{
List(0..<self.questions.count , id:\.self){ currentQuestion in
VStack{
Text(questions[currentQuestions])
// I want to show here the saved answer to each questions but here’s what I tried…..
//Text(saveAnswers()) -> Error :index out of range.
//Text(dictionary.dictionary[questions.questions[currentQuestion] ?? "")
//only show the last answer I answered, and when I used print I found that all questions
//are saved to the same answer.
}
}.sheet(isPresented: self.$isPresented, content: {
QuestionsSheet( currentQuestion: currentQuestion , dictionary :dictionary ,isPresented:
self.$isPresented ,questions :questions)
})
.onTapGesture{}
self.isPresented.toggle()
}
func saveAnswers()->String{
let values = Array(dictionary.dictionary.values.sorted())
return values[currentQuestion]
}
}
}
3- the question sheet
struct QuestionsSheet:View {
@ObservedObject var questions: Questions
@ObservedObject var dictionary: Dictionary
@State var currentQuestion: Int = 0
@Binding var isPresented: Bool
@State var answer: String = ""
var body: some View {
VStack{
Text("\(currentQuestion + 1)/ \(questions.questions.count)")
Text(self.questions.questions[currentQuestion])
TextField("Enter your Answer..", text: self.$answer)
Button {
self.nextQuestion()
self.saveAnswers()
} label: {
Text("Next")
}
}
}
func nextQuestion(){
if self.question <= (self.favoritesQuestionsData.favoritesQuestionsJson[category].favoritesQuestions.count - 1) {
self.question += 1
}
}
func saveAnswers() {
//HERE’S My PROBLEM
//All the answers of the answers are saved to the same value
dictionary.dictionary = [questions.questions[currentQuestion] : answer]
//using updateValue to be able to change the answer in the future
dictionary.dictionary.updateValue(answer, forKey:questions.questions[currentQuestion])
}
}
4- finally the dictionary..
//it works successfully
class Dictionary: ObservableObject {
@Published var dictionary = UserDefaults.standard.object(forKey: “answer”) as?
[String:String] ?? [:]{
didSet{
UserDefaults.standard.set(dictionary, forKey: “answer”)
}
}
}