Search code examples
iosswiftswift3alamofireimage

Index out of range data nil swift 3


I have data coming from Json and populating it inside an UIImage using alamofireImage. One of those elements that I am getting back from Json is a String that has a URL to an image. If a particular Json string is null or blank I get the following error :

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

Solution

  • Please never use ! operator without checks. I really suggest to use if let construction instead.

    Some pseudocode (I dont know your types) :

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

    And the initial error comes from this line print("jsonDict \(jsonDict![0].photo!)"), I guess, because you access object without check