focus focus - 1 month ago 14
iOS Question

swift: cannot subscript a value of type [Dictionary<String, AnyObject>] with an index of type string

I am trying to json parsing in swift 3. I am getting the above mentioned error. My parsing technique is as follows:

if let responseData = data {
do {
let json = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments)
if let dict = json as? [Dictionary<String, AnyObject>] {
if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String {

}
}
} catch {
print("could not serialize")
}
}


I am getting the error in the line:

if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String


please let me know how can I fix this issue

Answer

dict is actually arr. Create a loop to iterate thru it

if let arr = json as? [Dictionary<String, AnyObject>] {
   for item in arr {
      if let localityName = item["name"] as? String,
         let localityId = item["_id"] as? String {
         print(localityName, localityId)
      }
   }
}