当价值为零时我的应用程序崩溃我怎么能避免这种情况并让蛋糕[“赞”]可选?
我的代码
var likes = [[String:Any]]()
init(cake: [String: Any]){
self.likes = (cake["likes"] as! [String:Any])["data"] as! [[String:Any]]
}
答案 0 :(得分:2)
cake["likes"]
是可选的。标准方法是使用可选绑定。
var likes = [[String:Any]]()
init(cake: [String: Any]) {
if let likes = cake["likes"] as? [String:Any],
let data = likes["data"] as? [[String:Any]] {
self.likes = data
}
}
答案 1 :(得分:1)
试试这样: -
toString()
答案 2 :(得分:0)
您也可以使用Guard
var likes : [[String:Any]]?
init(cake: [String: Any]?){
guard let cakeV = cake,let likes = (cakeV["likes"] as? [String:Any]) ,let data = likes ["data"] as? [[String:Any]] else {
// IT is nil
return
}
likes = data
}