0

I have this struct to parse values from my api..

struct Deals {
    let title: String
    let detail: String

init(title : String, detail: String) {
        self.title = title
        self.detail = detail

}
}

Now I'm parsing the data from Alamofire in this format...

     if httpResponse.statusCode == 200 {

            if let result = response.result.value as? [String:Any] {
              guard let top = orderData["data"] as? [Any] else {
                                            return
               }
           for value in top {
             let aDict = value as? [String : Any]

             let title = aDict!["title"] as? String

             let detail = aDict!["description"] as? String

              let theDeals = Deals(title: title!, detail: detail!)
}
}
}

But some of these values have a nil value from server(for eg.detail is nil from server) and so it is causing a crash. I'm having difficulty using an if let properly so that the crash can be handled. Hope somebody can help...

1 Answers1

2

You are unwrapping the dict even if the parsing fail. Update to :

 if httpResponse.statusCode == 200 {


      guard let result = response.result.value as? [String:Any],
                let top = orderData["data"] as? [Any]
                else { return }

       for value in top {
        if  let aDict = value as? [String : Any],
            let title = aDict["title"] as? String,
            let detail = aDict["description"] as? String {
                let theDeals = Deals(title: title, detail: detail)
        } else {
        //parsing failed
        }
       }
  }
CZ54
  • 5,488
  • 1
  • 24
  • 39