I am trying to help a student with her coursework and we are having trouble getting a dictionary to work. We have used print statements to check that there is something in the dictionary and that the data is the correct data type for the key and value and it is but when we try and print the value from the key it prints nil.
It did work for a set of questions which were an array of question structures). Then we filtered these based on a topic(shown below ) and it stopped working
Any help gratefully received!
Here is the code:
mutating func makeGuessForCurrentQuestion(atIndex index:Int) {
//the answer index is stored in the dictionary data structure against the hash value of the currentQuestion (the question they just answered)
print(index)
print(type(of: index))
print(currentQuestion)
print(type(of: currentQuestion))
guesses[currentQuestion] = index
print("From inside Game Model\(guesses)")
print(guesses[currentQuestion])// Why is this showing nil when there is a value in it??
if let _ = guesses[currentQuestion]{
print("Not Nil")
}else{
print("Nil")
}
Here is the code where the values are put into the dictionary:
var guessWasMade: Bool {
//if there is a value in the dictionary, then it is true. If is not, then false
print("From GameViewModel \(game.guesses)")
if let _ = game.guesses[currentQuestion] {
return true
} else {
return false
}
}
This is where currentQuestion is coming from:
var currentQuestion: Question {
filteredQus[currentQuestionIndex]
}
And filtered questions are being created here
//FilteredQusAnd10Qus
private var filteredQus: [Question]{
var QuizQus: [Question] = []
var filteredQus: [Question] = []
filteredQus = questions.filter{$0.topic == "Energy"}
for i in 1...10{
var randQu = filteredQus.randomElement()//Select a random question
while QuizQus.contains(randQu!){
randQu = filteredQus.randomElement()
}
QuizQus.append(randQu!)
}
return QuizQus
}