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

标签 ios swift swift3 alamofireimage

我有来自 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/

相关文章:

ios - 如何在 iOS Couchbase Mobile 中使用 HTTPS 复制?

swift - 如何在 Swift 中的 NSTextView 中实现 NSTextFinderClient 协议(protocol)?

swift - 通用大中央调度

ios - 图表 lineChartDataset 舍入值

IOS Custom Segmented Pager - 使指示器滚动而不是标签

ios - 使用应用锁 MDM 配置文件检测 iOS 应用

ios - 当应用程序在后台运行/暂停时继续倒数计时器

ios - 如何防止在水平滚动方向上从左到右滚动 Collection View ?

ios - 使用 UIDocumentPickerViewController 时如何快速从 CSV 获取数据

ios - UIButton 选择器不工作