Mr_Vlasov
Mr_Vlasov

Reputation: 537

"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?

Upvotes: 1

Views: 10643

Answers (1)

perhapsmaybeharry
perhapsmaybeharry

Reputation: 894

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.

Upvotes: 2

Related Questions