Reputation: 175
I want to get array value by it's key.
I set the array with below code inside looping .
let que = Question(questionText: "\(questionWord)", options: quizAnsArr, correctAns: correctArrIndex, wrongAns: -1, isAnswered: false)
quizsArray += [que]
Now I get the below array. Here is my array.
[Kanji_Quiz.Question(questionText: "青", options: ["fast", "color", "heart", "blue"], correctAns: 3, wrongAns: -1, isAnswered: false), Kanji_Quiz.Question(questionText: "暑", options: ["owner", "heart", "hot (temperature)", "end"], correctAns: 2, wrongAns: -1, isAnswered: false)]
I was calling the value by using
print(quizsArray[questionText])
But it' show error. How can i call the value by index or smth. Please help me.
Upvotes: 1
Views: 96
Reputation: 2490
@Kawazoe Kazuke
quizsArray is of type [Question]... right ?
So By doing this: print(quizsArray[questionText])
, you're asking your program to go into the quizsArray: [Question]
and get the value where the index is equal to questionText
.
I don't see how that should NOT error.
If you don't want to change quizsArray from a [Question] to a native Swift Dictionary ([String:Any]), Then here's what you need to do:
• loop over the quizsArray. Something like this should do the job:
for question in quizsArray {
<code>
}
• only now will you have access to each question. so:
for question in quizsArray {
let text = question.getQuestionText()
if text.elementsEqual('questionText') {
let correctAnswerIndex = question.getQuestionAnswerIndex()
print(question.getQuestionAnswer(correctAnswerIndex))
}
}
• Please note that the method getQuestionAnswer(index: Int)
and getQuestionAnswerIndex()
is just methods i made up. You have to go and code your "getters and setters" where you created the Question class/struct
• So in the end, you should convert all that code to a fucntion where the parameters will be the (key) questionText and the function returns the right answer or even the whole object for that matter. Then you'll be set 👍🏽
Upvotes: 2
Reputation: 1909
At the first you should find the index of questionText and then print that element:
if let index = quizsArray.index(of: questionText) {
print(quizsArray[index])
}
But I suggest you to use Dictionary instead of array, you can achieve what you want in Dictionary easily.
Upvotes: 0