I am pretty new to coding so apologies if this should be straightforward for me.
I am using SwiftUI on Xcode, and am using JSON for my data.
I have the JSON file which contains just 7 items: 1 Int and 6 Strings (1 of those an array). I have a model file that maps the data items in JSON to SwiftUI variables. I have a data loader that reads the JSON file and does the correct error checking etc. I have a view that can show the data read from the JSON file.
I need to be able to read the data set for a specific record in the data. When I run my code currently I get the 1st item returned successfully but would now need to amend the code to be able to pull whichever record I require from the dataset.
let questions: [Question] = Bundle.main.decode("questions.json")
then in the body, I use this format to output any data item to the screen (question is one of the variable names defined in the model)
Text(question.question)
but of course, this only ever returns the first item in the JSON file. How do I read a specific data item please based on one of the items in the JSON file? ...
{
"id": 2,
"qn": "1",
"level": "1",
"sylabusItem": "1A2",
"question": "Dummy question 2",
"answers": ["Dummy answer 1", "Pretend answer 2", "Pretend answer 3", "Pretend answer 4"],
"correct": "2",
},
{
"id": 3,
"qn": "1",
"level": "1",
"sylabusItem": "1A2",
"question": "Dummy question 3",
"answers": ["Dummy answer 1", "Another answer 2", "Another answer 3", "Another answer 4"],
"correct": "4",
}
Model file
...
struct Question: Hashable, Codable, Identifiable {
var id: Int
var qn: String
var level: String
var sylabusItem: String
var question: String
var answers: [String]
var correct: String
static let allQuestions: [Question] = Bundle.main.decode("questions.json")
static let example = allQuestions[0]
}
Hope I have provided enough info. Thanks all.