Reputation: 1
I am working on a project and have reached a stage where I want to display data from a web service in a table view. My json data is in dictionary format and I am taking loop for fetching the data from dictionary by using key but it's getting the warning. So, please help me for this type of warning.
My loop is:-
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: []) as! NSDictionary
for eachFetchedRestaurant in fetchedData {
let eachRestaurant = eachFetchedRestaurant as! [String : Any]
let restaurantName = eachRestaurant["restName"] as! String
let restaurantImage = eachRestaurant["restaurant_image"] as! String
self.fetchedRestaurant.append(Restaurants(restaurantName: restaurantName, restaurantImage: restaurantImage))
}
print(self.fetchedRestaurant)
Getting warning on this line:-
let eachRestaurant = eachFetchedRestaurant as! [String : Any]
Cast from '(key: Any, value: Any)' to unrelated type '[String : Any]' always fails
Thanks in advance for helping!!!
Upvotes: 0
Views: 2053
Reputation: 4749
Since JSON response is array of (key, value)
format, so your fetch data should be of [[String:Any]]
format. Here is the updated code.
let fetchedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String:Any]]
for (key,eachFetchedRestaurant) in fetchedData {
let eachRestaurant = eachFetchedRestaurant as! [String : String]
let restaurantName = eachRestaurant["restName"] as! String
let restaurantImage = eachRestaurant["restaurant_image"] as! String
self.fetchedRestaurant.append(Restaurants(restaurantName: restaurantName, restaurantImage: restaurantImage))
}
print(self.fetchedRestaurant)
Upvotes: 1
Reputation: 285069
First of all don't use NSDictionary
and NSArray
in Swift, use native types.
You are applying array related enumeration API to a dictionary. The dictionary related API is
for (key, eachFetchedRestaurant) in fetchedData
You've got two options:
fetchedData
is indeed expected to be dictionary then cast
let fetchedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
and use the mentioned enumeration API
(the more likely one) fetchedData
is expected to be an array then you have to cast
let fetchedData = try JSONSerialization.jsonObject(with: data!) as! [[String:Any]]
Upvotes: 0