Reputation: 35
I'm trying to print the individual members of Results after parsing JSON data and assigning it to Question.
struct Question: Decodable
{
let response_code: Int
let results: [Results]
}
struct Results: Decodable
{
let category: String
let question: String
let correct_answer: String
let incorrect_answers: [String]
}
I tried using:
print(question.results)
But I get:
[Trivia_Game.Results(category: "Entertainment: Music", question: "Which of the following bands is Tom DeLonge not a part of?", correct_answer: "+44", incorrect_answers: ["Box Car Racer", "Blink-182", "Angels & Airwaves"])]
How do I access the individual members such as "category" or "question"?
Upvotes: 0
Views: 135
Reputation: 166
You would have to first access an individual element of question.results
, like so:
question.results[n] // where n represents a valid array index number
And then to access specific properties of that individual Results
structure, you would do it in the same way as you would access the value of a property of any other struct. For example, if you wanted to get the value of the category
member of a Results
structure, you would do this:
question.results[n].category
And then if you wanted to print the value of that specific member (again, using the category
member as an example), you would do this:
print(question.results[n].category)
Now, if you wanted to print out the value of the category
member for each of the Results
structures in the question.results
array, then you could use a for loop like so:
for result in question.results {
print(result.category)
}
Hope that helps.
Upvotes: 1
Reputation: 285069
results
is an array. You have to enumerate the array
let results = question.results
for result in results {
print(result.category, result.question)
}
or
question.results.forEach { print($0.category, $0.question) }
Upvotes: 1