In this example, I am creating a new empty array of Int and I want to add certain characters from the other array into it. Originally, in my characters array I store numbers ["1","","2","","3"] and in this array (I might be doing this completely wrong) I want to iterate through those numbers to produce a newarray which will have these numbers [1,2,3] (essentially removing the spaces in between and making them of type Int)
As far as I understand, I have created a dynamic array i.e. no specific size, but I am getting this error : fatal error: Array index out of range and I am not sure why. Could someone clarify this for me? Thanks
do{
var data = try String(contentsOfFile: documentsDirectoryPath as String,
encoding: NSASCIIStringEncoding)
print(data)
let characters = Array(data.characters)
print(characters)
var newarray = [Int]()
for var index = 0; index <= characters.count ; ++index {
if characters[index] == " " {
index++
}
else{
newarray[index] = index
}
}
print(newarray)
}
catch{
print("error")
}
}
newarray[index] = indexif characters[index] == " " {index++}. You're incrementing twice if this happens. The for loop already increments the value for you. Also a nicer way of writing the loop would befor index in 0..<characters.count {}. As also pointed out, you should useappendto add items to your new array.1, 2, 3in the output have anything to do with"1", "2", "3"from the input? Would output from["A", " ", "B", " ", "C"]array be any different?"1", "2", "3"into integers hence why i removed the" "in my output. I am only storing numbers in that array but inStringtype for now. So your["A", " ", "B", " ", "C"]for this particular scenario would be["A", "B", "C"]but I want to store onlyIntegersso that wouldn't work in my case