Rewan
Rewan

Reputation: 75

Cannot downcast from ... to a more optional type

First of all I've got "ApiModel" protocol, which is simply empty. Then I've got model struct "Pokemon", which implements ApiModel protocol. Now I'm trying to convert array of ApiModel ( [ApiModel] ) to array of Pokemon [Pokemon], so I'm using this function:

if let pokemonsList = objects as! [Pokemon]? {
                        self.pokemons = pokemonsList
                    }

objects - is non optional let variable, which holds [ApiModel].

But I've got following error: Cannot downcast from '[ApiModel]' to a more optional type '[Pokemon]?'

When I'm trying to do that on single model it's working fine:

if let poke = objects.first as! Pokemon? {
                        self.pokemon = poke
                    }

Also, if objects will be optional - again it's working fine.

Can you help me to understand why arrays doesn't works?

Upvotes: 0

Views: 703

Answers (1)

ManWithBear
ManWithBear

Reputation: 2875

You had mistake in if let syntax. Instead of force cast you want to have optional cast. And since you already have this array you don't want get optional array of pokemons

if let pokemonsList = objects as? [Pokemon] {
    self.pokemons = pokemonsList
}

Upvotes: 3

Related Questions