索引超出范围数据 nil swift 3

Index out of range data nil swift 3

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

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!)"),我猜,因为你访问对象时没有检查

我想,你没有检查它是否为空

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

                  }
                }
            })
        }