I am getting an index out of range error from the data received from the API, how can I solve it?

44 Views Asked by At

This fetch data https://pokeapi.co/api/v2/pokemon/(id)/ id (1,2,3,4,5....) When I click on cells in the table view, I get information in some cells and index errors in others.

DetailViewController func ConfigureView()

private func configureView() {
        viewModel?.fetchPokemonDetails(completion: { [weak self] in
            guard let self = self else { return }
            DispatchQueue.main.async {
                self.nameLabel.text = "Name: \(self.viewModel?.name ?? "")"
                self.abilitiesNameLabel.text = "Abilities: \(self.viewModel?.abilities?[0].ability?.name ?? "")"
                if let ability = self.viewModel?.abilities?[1] { // this line I wanted to use if but it didn't work
                    self.abilitiesNameLabel2.text = "Abilities: \(ability.ability?.name ?? "")" // this line
                }
                
                self.typeLabel.text = "Type: \(self.viewModel?.types?[1].type?.name ?? "")" // sometimes it gives error here every time index out of range error
                self.statLabel.text = "Stat: \(self.viewModel?.stats?[0].baseStat ?? 0)"
                
                
                if let imageURL = self.viewModel?.imageURL {
                    self.imageView.sd_setImage(with: imageURL)
                }
            }
        })
    }

enter image description here

DetailViewModel

var abilities: [Ability]?
    var stats: [Stat]?
    var types: [TypeElement]?
    
    var pokemonId: String
    let apiService: PokeAPIService
    var name: String?
    var imageURL: URL?
    
    // MARK: - Initializers
    init(pokemonId: String,name: String?,imageURL: URL?,apiService: PokeAPIService) {
        self.pokemonId = pokemonId
        self.apiService = apiService
        self.imageURL = imageURL
        self.name = name
    }
    
    // MARK: - Public Methods
    
    func fetchPokemonDetails(completion: @escaping () -> Void) {
        apiService.getPokemon(by: pokemonId) { [weak self] response in
            guard let self = self else { return }
            self.name = response.name
            self.abilities = response.abilities
            self.types = response.types
            self.stats = response.stats
            if let urlString = response.sprites?.other?.officialArtwork?.frontDefault {
                self.imageURL = URL(string: urlString)
            }
            completion()
        }
    }

I tried to do it as if let, I searched on the internet and stackoverflow, but when I examined it with breakpoint, it kept giving the same error.

0

There are 0 best solutions below