1

I am having a problem with array in Swift, I want to make an array like this :

var Test : [[String]] = [[]]
let test_string = "HELLO"

   for var i = 0; i <= 15; ++i {
      for x in test_string.characters {
         Test[i].append("\(i)\(x)")
      }
   }

print(Test[1][1]) // This should print 1E

but this always gives me this error ! :

fatal error: Array index out of range

What I am missing here ?

1
  • You're missing to append anything to Test, There is no Test[0] when executing Test[i].append("\(i)\(x)") Commented Apr 13, 2016 at 16:42

1 Answer 1

3

Your array of arrays is empty, so there is no Test[0] (technically you initialize it to [[]] which means it has one element, so Test[0] does exist, but then Test[1] doesn't, which is confusing). You need to initialize each element to an empty array:

var Test : [[String]] = [] // This really should be an empty array for consistency.
let test_string = "HELLO"

   for var i = 0; i <= 15; ++i {
      Test.append([]) // <== initialize the array
      for x in test_string.characters {
         Test[i].append("\(i)\(x)")
      }
   }

print(Test[1][1]) // This should print 1E

This isn't very good Swift, though. C-style for loops are deprecated (also, variables should always be camelCase, never leading caps or using underscores).

This can be translated nicely into a nested mapping:

let testString = "HELLO"
let indexedCharacters = (0..<15).map { i in
    testString.characters.map { c in "\(i)\(c)" }
}

This maps the numbers 0-15 into arrays of strings based on the characters. Once you understand the basics of map, this should be much easier to comprehend than the original loop. (I'm not saying that map is better than for in general. Often a simple for-in loop is best. But for such a simple mapping, map is very clear and uses Swift's features nicely.)

Sign up to request clarification or add additional context in comments.

5 Comments

Fixed; it's append(). This is not good Swift, though. I'm thinking about how to improve it.
yes now working :) .. but why its not good swift , in terms of what , can you explain to me please i am new to swift :)
Also, array names should be plural. Although I am not sure what they should be when they are nested. Good answer.
@Caleb Agreed. Tried to pick a better name, though I'm not sure what this array would ever be used for, so I'm not sure that's the best name either. :D
yes most of the time i use lower case but from now on it will be always lol.. thanks for your explanation :) ,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.