结构
我试图重新创建 Chris Edihoff 在 dotSwift 2016 Demo 中给出的演示代码。这是代码。
struct List {
let name:String
let id:Int
}
extension List {
init?(json: [String:AnyObject]) {
guard
let name = json["name"] as? String,
let id = json["id"] as? Int else
{
return nil
}
self.name = name
self.id = id
}
}
let listData = json["data"] as? [[String:AnyObject]]
到目前为止,一切似乎都很好。但这就是问题所在。他做了这样的事情:
let list:[List] = listData.flatMap(List.init)
上面的行应该返回列表对象数组。Chris Edihoff 似乎没有任何问题,但是当我这样做时,Xcode 会发出警告
- flatMap 产生'U?',而不是预期的上下文结果类型'_?
还有什么在List.init
这里?我从未见过这种初始化对象的方式。应该是List()
,或者如果我们在这里使用客户初始化,应该是List(json:someObject)
对的?
参考 Chris Edihof 谈话:https ://www.youtube.com/watch?v=ewk-XNzXzAA