0

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”)
        }
    }
}
Yrb
  • 8,103
  • 2
  • 14
  • 44
  • Does this answer your question? [Save dictionary to UserDefaults](https://stackoverflow.com/questions/49843701/save-dictionary-to-userdefaults) – Joakim Danielson Dec 03 '20 at 08:43
  • Not really , first because i use swiftui , second no that's not what i was asking for. Thanks tho – ThurayaOtto Dec 04 '20 at 20:23
  • 1
    You say in the code comments that your problem is saving the dictionary properly so I thought that was the root problem but if it isn’t I don’t really understand what you are asking. – Joakim Danielson Dec 04 '20 at 21:51

0 Answers0