显示swiftUI中来自服务器的数据的列表



我从服务器抓取数据,我需要显示它像显示在这个网站SwiftUI -嵌套列表

来自服务器的数据

"OptionsListByItemId": [
{
"Choices": [
{
"ChoiceId": 1284226,
"ChoiceName": "Hot",
},
{ 
"ChoiceId": 1284227,
"ChoiceName": "Cool",
}
],
"OptionId": 187472,
"OptionName": "Temperature"
},

{ 
"Choices": [
{
"ChoiceId": 1284223,
"ChoiceName": "61%",
},
{ 
"ChoiceId": 1284224,
"ChoiceName": "70%",
}
],
"OptionId": 187473,
"OptionName": "Humidity"
]
}

我的模型就像

struct OptionsandChoices : Decodable , Identifiable{

var id: String{OptionName}
var OptionName: String!
var OptionId: Int
var Choices : [ChoiseList]

}
struct OptionsandChoiceList: Decodable{

var OptionsListByItemId:[OptionsandChoices]  
}
struct ChoiseList: Decodable {
var ChoiceName: String!
var ChoiceId: Int
}

ViewModel是

class ItemChoiceViewModel : ObservableObject{
@Published var OpnChoice: OptionsandChoiceList = OptionsandChoiceList(OptionsListByItemId: [])
// fetching data from server 
}

我的swiftUI视图就像

struct ItemView: View {
var OpnChoice = OptionsandChoiceList(OptionsListByItemId: [])
@ObservedObject var choicevwModel = ChoiceViewModel()
struct Optionspage: View {
var body: some View {
List(choicevwModel.OpnChoice.OptionsListByItemId) {opn in 
Text(opn.OptionName)
}
}

我无法在列表中使用ChoiceName

我怎样才能在OptionName下面的每一行得到choiceName,就像我给的链接

List应该显示为

Temperature 
Hot 
Cold 

Humidity
61%
70%

目前我得到两行

Temperature
Humidity

您要查找的属性位于Choices中。要获取它的值,可以这样写:

opn.Choices[yourIndex].OptionName

同样,如果你想使用@ObservedObject,让你的OptionsandChoiceList类代替结构,并使其符合ObservableObject协议。最后,在这里声明@Published属性。

final class OptionsandChoiceList: ObservableObject, Decodable {
@Published var OptionsListByItemId: OptionsandChoices = []  
}