我有这个结构来解析我的api中的值..
struct Deals {
let title: String
let detail: String
init(title : String, detail: String) {
self.title = title
self.detail = detail
}
}
现在我正在以这种格式解析Alamofire的数据......
if httpResponse.statusCode == 200 {
if let result = response.result.value as? [String:Any] {
guard let top = orderData["data"] as? [Any] else {
return
}
for value in top {
let aDict = value as? [String : Any]
let title = aDict!["title"] as? String
let detail = aDict!["description"] as? String
let theDeals = Deals(title: title!, detail: detail!)
}
}
}
但是这些值中的一些值与服务器的值为零(因为eg.detail是来自服务器的nil),因此导致崩溃。我在使用if let
时遇到了困难,因此可以处理崩溃。希望有人能帮忙......
答案 0 :(得分:2)
即使解析失败,您也会解开dict
。
更新至:
if httpResponse.statusCode == 200 {
guard let result = response.result.value as? [String:Any],
let top = orderData["data"] as? [Any]
else { return }
for value in top {
if let aDict = value as? [String : Any],
let title = aDict["title"] as? String,
let detail = aDict["description"] as? String {
let theDeals = Deals(title: title, detail: detail)
} else {
//parsing failed
}
}
}