DrWurffius DrWurffius - 17 days ago 6
iOS Question

Cannot subscript a value of type '[[String : AnyObject]]' with an index of type 'String'

I'm trying to get the temprature for a specific location, but while trying to extract the info from the JSON i'll find this error:


Cannot subscript a value of type '[[String : AnyObject]]' with an index of type 'String'


The code:

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]

if let mainDictionary = json["main"] as? [[String : AnyObject]]
{

if let temp = mainDictionary["temp"] as! String
{
print(temp)

}
}


The error appears at the line:

if let temp = mainDictionary["temp"] as! String


I've tried multiple 'solutions' found on slack but none seem to work...

Thanks in advance!

Answer

You are casting the type as:

[[String: AnyObject]]

When you should be casting it like this:

[String: AnyObject]

The way you are doing it casts the type as an array of arrays that contain dictionaries when you should want to cast it as an array of dictionaries that contain a key as a strong and any object as a value.

Hope this helped :)

Comments