How do I set “children” from below JSON object? I retrieve data from an API and would like to create a hierarchical list (collapsing cells).
Thanks in advance.
E.g.
File1.swift
struct Structure1: Decodable {
let items: [Structure2]
}
struct Structure2: Decodable, Identifiable {
let id = UUID()
let itemName: String
var children: [Structure2]? = nil // <-- how to set?
}
File2.swift
class File2: ObservableObject {
@Published var items: [Structure2] = []
func callAPI() {
// ... some code ...
do {
let response = try JSONDecoder().decode(Structure1.self, from: json)
self.items = response.items
}
}
}
ContentView.swift
{
@StateObject private var model = File2()
var body: some View {
List(model.items, children: \.children) { item in
Text(item.itemName)
}
.onAppear {
model.callAPI()
}
}
}
JSON
{
"totalItems": 2,
"items": [{ // <-- what I would like to display in sub cells
"id": 1,
"itemName": "item1",
"subItems": [{
"id": 1,
"name": "subItem1"
}, {
"id": 2,
"name": "subItem2",
"otherInfo": "text"
}],
"a0": []
}, {
"id": 2,
"itemName": "item2",
"subItems": [{
"id": 1,
"name": "subItem1"
}, {
"id": 2,
"name": "subItem2",
"otherInfo": "text"
}],
"a0": []
}]
}