Now I am working on extracting the first name of the ability
I am having an issue trying to get to arrays that are nested inside a json array here is an example of what I mean. how do I get down to one ability and store that information in an array or dictionary?
Swift
pokemonDictionary!["abilities"] this returns the following Json code
now how do I store the first ability in a dictionary or whatever type is appropriate?
I want to store that ability in a variable and then pull the ability out and store that into another variable
any help is much appreciated..I tried looking this up but I couldn't find anything
I have tried the following:
print(pokemonDictionary!["abilities"]![0])
this gives an error "Type 'Any' has no subscript members"
If you are storing JSON in [String : Any], you obviously can't do dict["ability"]["something else"] if an ability is another dictionary, since Any – the type under which you store the values of your dictionary – doesn't have subscripts.
You will have to force-cast first: (dict["ability"] as! [String: Any])["something else"].
Alternatively, you can use frameworks that are designed to work with JSON if you want your code to be more tidy, safe and readable. SwiftyJSON, for instance.
let ability1 = dict[0] as! [String: AnyObject]
ability1["name"] // Is this what you want?
Now, because you have an ability inside the ability (...), you will have to go deeper:
func getAbilities(from dict: [String: Any]) {
let abilities = dict["abilities"] as! NSArray
let firstAbility = abilities[0] as [String: Any]
let actualFirstAbility = firstAbility["ability"] as [String: Any]
let name = actualFirstAbility["name"]
}