gpt4 book ai didi

ios - 索引超出范围数据 nil swift 3

转载 作者:行者123 更新时间:2023-11-28 09:40:51 25 4
gpt4 key购买 nike

我有来自 Json 的数据,并使用 alamofireImage 将其填充到 UIImage 中。我从 Json 返回的元素之一是一个包含图像 URL 的字符串。如果特定的 Json 字符串为 null 或空白,我会收到以下错误:

fatal error: Index out of range

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!)!)
}
}
})
}

最佳答案

请不要在没有检查的情况下使用 ! 运算符。我真的建议改用 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!)") 这行,我猜是因为你访问对象时没有检查

关于ios - 索引超出范围数据 nil swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48337078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com