Reputation: 610
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 ?
Upvotes: 1
Views: 1297
Reputation: 299345
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.)
Upvotes: 3