gpt4 book ai didi

ios - 对象列表总是在 swift 中打印 nil

转载 作者:行者123 更新时间:2023-11-30 12:37:24 25 4
gpt4 key购买 nike

在我的对象 Dish xxx.Dish 中,我想访问 Choicepricename显示但我失败了。从Web API加载菜数据,我测试了数据加载成功,并将数据放入对象菜中,并将对象列表返回到viewcontroller以加载tableview。

打印控制台的输出

Optional([xxx.Dish, xxx.Dish])

并在菜品类中附加optionList?.append(_obj)

之前

xxx.DishOption

任何人都可以帮助我,我该怎么做..我是 swift 的新手,这是正确的实现方式吗?请建议我?

class Dish {
let dishId : String
var optionList : [DishOption]?

init?(fromAPIResponse resposne : Dictionary<String,AnyObject>) {

guard let dishId = resposne["dishId"] as? String else {
return nil

}
self.dishId = dishId
if let objs = resposne["options"] as? [[String: AnyObject]]{

for obj in objs {
if let _obj = DishOption(fromAPIResponse: obj){

optionList?.append(_obj)

}
}
}
}

class DishOption {

let optionId : String

var choiceList : [Choice]?

init?(fromAPIResponse resposne : Dictionary<String,AnyObject>) {

guard let optionId = resposne["optionId"] as? String else {
return nil
}

self.optionId = optionId

if let objs = resposne["choices"] as? [[String: AnyObject]]{

for obj in objs {
if let _obj = Choice(fromAPIResponse: obj){

choiceList?.append(_obj)

}
}
}
}
}

class Choice{

let choiceId : String
let name : String
let price : String

init?(fromAPIResponse resposne : Dictionary<String,AnyObject>) {
guard let choiceId = resposne["choiceId"] as? String ,
let name = resposne["name"] as? String,
let price = resposne["price"] as? String else {

return nil
}
self.choiceId = choiceId
self.name = name
self.price = price

}

}

更新:

     var  dishMenuList = [Dish]()
guard let objs = json["menu_list"] as? [[String : AnyObject]] else {
return
}

for obj in objs {

if let _obj = Dish(fromAPIResponse: obj){

print(_obj.optionList) //always print nil


if let options = _obj.optionList {

for data in options {

print(data.displayAsButton)

}
}
dishMenuList.append(_obj)
}

}

最佳答案

据我所知,您永远不会同时初始化 optionList 和 choiceList 数组。最好将它们初始化为空数组:

class Dish {
let dishId : String
var optionList = [DishOption]()
...

optionList.append(_obj)

这就是您看不到任何选项的原因。由于 optionList 仍然为 nil,因此 optionList?.append(_obj) 行不会执行。

关于ios - 对象列表总是在 swift 中打印 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42699642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com