I’m working with a nested JSON API response and trying to display one question at a time in my table view. Right now I can navigate through the first level of nested data but I’m stuck when trying to move to the next question in the sequence.
Currently I’m at this question:
{
"choice": 1234,
"assessment": 100,
"id": 501,
"title": "What's your favorite pizza topping?",
"choices": [],
"description": "",
"type": "rating",
"creator": 3
}
But I need to navigate to the next question like this:
{
"choice": null,
"assessment": 100,
"id": 502,
"title": "Tell us about your weekend plans",
"choices": [],
"description": "",
"type": "free_text",
"creator": 3
}
Here’s my current implementation:
func traverseNestedData(_ questions: [SurveyQuestion]?) -> [Int: QuestionItem] {
guard let questions = questions else {
return [:]
}
var resultDict: [Int: QuestionItem] = [:]
for question in questions {
let questionItem = QuestionItem(id: question.id,
title: question.title,
description: question.description,
type: question.type,
assessment: question.assessment,
options: convertOptions(question.options),
choice: question.choice,
creator: question.creator)
resultDict[question.id] = questionItem
if let options = question.options {
for option in options {
let nestedData = traverseNestedData(option.subQuestions)
nestedData.forEach { (key, value) in
resultDict[key] = value
}
}
}
}
questionDict = resultDict
return resultDict
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return surveyData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SurveyCell", for: indexPath) as? SurveyTableCell else { return UITableViewCell() }
cell.questionLabel.text = surveyData[indexPath.row].options?[indexPath.row].title
return cell
}
struct SurveyQuestion: Codable {
let id: Int
let title, description, type: String
let assessment: Int
let options: [QuestionOption]?
let choice: Int?
let creator: Int
}
struct QuestionOption: Codable {
let id: Int
let title: String
let category: String
let question: Int
let subQuestions: [SurveyQuestion]?
}
The problem is my code isn’t properly navigating through the nested structure. How can I modify this to show one question at a time and move between them correctly?