【发布时间】:2018-01-19 08:43:19
【问题描述】:
我有来自 Json 的数据并使用 alamofireImage 将其填充到 UIImage 中。我从 Json 得到的其中一个元素是一个具有图像 URL 的字符串。如果特定的 Json 字符串为空或空白,我会收到以下错误:
致命错误:索引超出范围
EventEngine.getEventGalery(invitedID, limit: "2") { (result, error) in
DispatchQueue.main.async(execute: { () -> Void in
if let response = result as? EventGaleryResponse{
self.galery = response.data!
let jsonDict = self.galery
print("jsonDict \(jsonDict![0].photo!)")
if jsonDict![0].photo != nil {
self.imagearry1.af_setImage(withURL: URL(string: jsonDict![0].photo!)!)
}
if jsonDict![1].photo != nil {
self.imagearry2.af_setImage(withURL: URL(string:jsonDict![1].photo!)!)
}
if jsonDict![2].photo != nil {
self.imagearry3.af_setImage(withURL: URL(string: jsonDict![2].photo!)!)
}
}
})
}
【问题讨论】:
-
您正在获取 jsonDict 的第一个元素,使用“jsonDict[0]”,但您没有检查它是否为空。 jsonDict 可以不为空,也可以为空。
-
jsonDict![0]命名一个 var Dict 实在是太烦人了,而实际上它似乎是一个数组。由于它是一个数组,jsonDict![2]可能会导致崩溃,因为您没有检查它是否至少有 3 个元素......(其他元素依此类推)。 -
感谢您的回答。如何检查它是否为空?
标签: ios swift swift3 alamofireimage