在我的对象Feed xxx.Dish
中,我想要访问选择类price
和name
来显示但我失败了。来自Web API的数据加载,我测试了数据加载成功,并将数据放到对象盘中,并将对象列表返回到 viewcontroller 以加载tableview。
打印控制台的输出
可选([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)
}
}
答案 0 :(得分:0)
从我所看到的,你永远不会初始化optionList和choiceList数组。将它们初始化为空数组会更好:
class Dish {
let dishId : String
var optionList = [DishOption]()
...
optionList.append(_obj)
这就是您看不到任何选项的原因。由于optionList仍为nil,因此行optionList?.append(_obj)
不会执行。