While fetching data from api I can get response either array of products or dictionary with error for e.g.
If everything went right api sends array of products as:
[ "Product1": { name = "someting", price = 100, discount = 10%, images = [image1,image2] }, "Product2": { name = "someting", price = 100, discount = 10%, images = [image1,image2] } ]
But if some error occur it sends dictionary with error message and code as:
{ error_message = "message" error_code = 202 }
I am using this code to convert JSON data to array:
do {
let jsonDict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray{
//Some code....
} catch let error as NSError {
print("JSON Error: \(error.localizedDescription)")
}
but if I get error as dictionary it crash.
Problems: 1. How to know whether received data is an array or dictionary ? 2. Some time even key or value can be missing so checking for value it becomes very lengthy code like:
if let productsArray = jsonObject as? NSArray{
if let product1 = productsArray[0] as? NSDictionary{
if let imagesArray = product1["image"] as? NSArray{
if let imageUrl = imagesArray[0] as? String{
//Code ....
}
}
}
}
I read about guard keyword to reduce if condition but I don't have clear idea how to use here.