Mr_Vlasov Mr_Vlasov - 2 months ago 7
Swift Question

"Cannot Subscript a value of type '[String]' with an index of type 'String' "

Swift 3.0

Got this error: "Cannot Subscript a value of type '[String]' with an index of type 'String' "

when I tried to loop through an array "pokemon" of Strings:

for x in pokemon {

var name: String!
name = pokemon[x]

poke = Pokemon(name: name, pokemonId: x)

pokemons.append(poke)
}


However, it worked when I wrote:

for x in 1..<pokemon.count {

var name: String!
name = pokemon[x]
poke = Pokemon(name: name, pokemonId: x)
pokemons.append(poke)
}


After researching, it seems that "for x in pokemon" makes "x" not an Int, but a String (actual array elements).
Why this happens?

Answer

In your first loop, you are doing

for x in pokemon

This casts each value in pokemon to x.

You don't need to subscript pokemon[x] as x is not an index, it is the element.

Naturally, you would get the error you got because: - pokemon is an array of strings - x is an element in pokemon (which makes it a string).

With this loop, this is happening in your code:

pokemon["snorlax"]

As arrays are subscriptable only by integer, this is invalid.

For this loop, one only needs to

name = x

to cast the value of the currently iterated element of pokemon to the variable.


In your second loop, you're iterating through an integer sequence (range).

for x in 1..<pokemon.count

The range 1..<pokemon.count gives x the value of 1, 2, 3... and so on per iteration until you reach one less than the count of Pokemons in the array.

This works because you are now subscripting array pokemon to an integer value of x.

With this loop, this is happening in your code:

pokemon[1] // contains string "snorlax"`

Also, I'm not sure if this is a mistake in your code but starting the range at 1 means that you'll exclude the first element of a zero-indexed array, in which the first element is 0.