问题描述
我有以下 JSON 响应。
{
"results":[
{
"TrimName":"Truck","VIN":"GTJ3E18JF164623","Price": 47600,"odometer": 35511,"odometerType": "Miles","OptionCodeSpecs":{
"C_Specs":{
"code":"C_Specs","name":"Specs","options":[
{
"code":"Specs_acceleration","name":"5.2 sec","long_name":"5.2 seconds","description":"0-60 mph"
},{
"code":"Specs_TOP_SPEED","name":"140 mph","long_name":"140 miles per hour","description":"Top Speed"
},{
"code":"Specs_RANGE","name":"264 mi","long_name":"264 miles","description":"range (EPA)"
}
]
}
}
}
],"total_matches_found":"53"
}
我使用 app.quicktype.io 构建了 Struct。
// MARK: - InventoryModel
struct InventoryModel: Codable {
let results: [Result]
let totalMatchesFound: String
enum CodingKeys: String,CodingKey {
case results
case totalMatchesFound = "total_matches_found"
}
}
// MARK: - Result
struct Result: Codable {
let trimName,vin: String
let price,odometer: Int
let odometerType: String
let optionCodeSpecs: OptionCodeSpecs
enum CodingKeys: String,CodingKey {
case trimName = "TrimName"
case vin = "VIN"
case price = "Price"
case odometer = "odometer"
case odometerType = "odometerType"
case optionCodeSpecs = "OptionCodeSpecs"
}
}
// MARK: - OptionCodeSpecs
struct OptionCodeSpecs: Codable {
let cSpecs: CSpecs
enum CodingKeys: String,CodingKey {
case cSpecs = "C_Specs"
}
}
// MARK: - CSpecs
struct CSpecs: Codable {
let code,name: String
let options: [Option]
}
// MARK: - Option
struct Option: Codable {
let code,name,longName,optionDescription: String
enum CodingKeys: String,CodingKey {
case code,name
case longName = "long_name"
case optionDescription = "description"
}
}
我能够成功检索到 JSON 响应。
@Published var getInventoryQuery: InventoryModel = InventoryModel(results: [],totalMatchesFound: "")
在我的 ContentView 中,我能够在 Results 对象中显示数据,但我无法访问 OptionCodeSpecs 对象中的 options 数组而不会出现以下错误:
编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式
Xcode 版本 12.5.1 (12E507)
@Observedobject var inv = GetInventory()
ScrollView(.horizontal,showsIndicators: false){
HStack(spacing: 10){
ForEach(inv.getInventoryQuery.results,id: \.trimName) { inventory in
vstack(alignment: .leading) {
vstack(alignment: .center) {
Text(inventory.trimName)
但是,当我尝试访问选项数组时,出现以下错误:
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
HStack(alignment: .center){
ForEach(inv.getInventoryQuery.results[inventory].optionCodeSpecs.cSpecs.options) { options in
Text(options.longName)
.font(.headline)
.fontWeight(.light)
Image(systemName: "battery.100")
.renderingMode(.original)
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)