我有来自Json的数据,并使用alamofireImage在UIImage中填充它。我从Json回来的其中一个元素是一个String,它有一个图像的URL。如果特定的Json字符串为null或空白,则会出现以下错误:
致命错误:索引超出范围
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!)!)
}
}
})
}
答案 0 :(得分:4)
请勿在未经检查的情况下使用!
运营商。我真的建议改为使用if let
构造。
一些伪代码(我不知道你的类型):
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
if let dict = jsonDict {
setPhotoFromDict(dict, 0, self.imagearry1)
setPhotoFromDict(dict, 1, self.imagearry2)
setPhotoFromDict(dict, 2, self.imagearry3)
} else {
print("cannot deserialise \(String(describing: jsonDict)")
}
}
})
}
private func setPhotoFromDict(<#DictType#> dict, Int index, <#ImageArrayType#> imageArary) {
if let photo = dict[index].photo as? String, let url = URL(string: photo) {
imageArary.af_setImage(withURL: url)
}
}
初始错误来自此行print("jsonDict \(jsonDict![0].photo!)")
,我想,因为你没有检查就访问了对象
答案 1 :(得分:2)
我认为,你没有检查它是否为空
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
if jsonDict != nil {
if jsonDict.count > 0 && jsonDict![0].photo != nil {
self.imagearry1.af_setImage(withURL: URL(string: jsonDict![0].photo!)!)
}
if jsonDict.count > 1 && jsonDict![1].photo != nil {
self.imagearry2.af_setImage(withURL: URL(string:jsonDict![1].photo!)!)
}
if jsonDict.count > 2 && jsonDict![2].photo != nil {
self.imagearry3.af_setImage(withURL: URL(string: jsonDict![2].photo!)!)
}
}
}
})
}