How to Call URL in API Nested Array

I'm new to REST API and am having some trouble. I'm trying to call data from an array that's nested within a dictionary. While I've been able to pull data from other variables fine, this is giving me some problems. For reference, the URL I need is labeled "front default," inside the "sprites" array. Furthermore, the URL is that of an image, and I am using Alamofire Image to display images. I will include the code I've used thus far to call other variables, along with a link to the API.


https://pokeapi.co/api/v2/pokemon/pikachu/


import Foundation
import Alamofire
import AlamofireImage
import SwiftyJSON
import Siesta
class PokeInfo {
    var name: String
    var id: Int
    var abilities: [String]
    var types: [String]
  
   
    /
    init?(jsonDictionary: [String: Any]) {
        /
        guard let name = jsonDictionary["name"] as? String,
            let id = jsonDictionary["id"] as? Int,
            /
            let abilities = jsonDictionary["abilities"] as? [[String: Any]],
        let types = jsonDictionary["types"] as? [[String: Any]]
        else {
                return nil
        };
       

        var abilityNames: [String] = []
         var typeNames: [String] = []
       
        /
        for abilityDictionary in abilities {
           
            guard let ability = abilityDictionary["ability"] as? [String: Any], let name = ability["name"] as? String else { break }
           
            abilityNames.append(name)
        };
        for typeDictionary in types {
           
            guard let type = typeDictionary["type"] as? [String: Any], let name = type["name"] as? String else { break }
           
            typeNames.append(name)
        }
       
        self.name = name
        self.id = id
        self.abilities = abilityNames
        self.types = typeNames
    }
}

Replies

Which is the line that does not work ?


For readability of your code, you should avoid to reuse the same names, in particular for different types of objects. It is not forbidden but much more painful to read.

  1. var abilities: [String] // Here an array of strings
  2. let abilities = jsonDictionary["abilities"] as? [[String: Any]] // Here an array if dictionaries