Array index out of range [swift] - arrays

I have a set of Strings, which I split it out and save it into an Array, and try to loop it with api as a parameter, but it keep crash with error
index out of range
why is it? Need help pls

You should learn about array basic ideas. This error shows becuse the item you request is not available in the array.
for i in 0...qrCoderArrau.count - 1 {
}

The error is because you are trying to access an element in array with an index greater than its size - 1.

Your qrCodeArray Array is empty also you need to for loop less one to the count of qrCodeArray. So change you for loop like this.
for i in 0..<qrCodeArray.count {
}
In your case for i in 0...qrCoderArray.count { it will execute for loop if your qrCoderArray.count is 0.

To avoid those errors (the last index of an array is count-1) use always
for qrCode in qrCodeArray { ...
rather than an index loop and even if you need the index use
for (index, qrCode) in qrCodeArray.enumerate() { ...

I think best solution is foreach in these situations
for qr in qrCoderArray {
...
}

Related

Get first entry in Swift array

I can't seem to find much online, but how can I get the first (and then second and third, later on) entry of an array?
My array is being saved to UserDefaults elsewhere and then pulled for use here.
Thanks!
Did you mean to loop through the elements? You can use for in or forEach for that.
var array: [MyType]
for element in array {
print(element)
}
array.forEach { element in
print(element)
}
Maybe you are trying to iterate value from continually with index also
Here is two way you can get first index value than second index value third index value with index also . hope you will get your result .
First way :
var stringArray = ["a","b","C","D","a","i","x","D"]
for (index, element) in stringArray.enumerated() {
print("Item \(index): \(element)")
}
Another way :
for index in 0 ..< stringArray.count {
print(stringArray[index])
}
let me know if its help you.

Is it safe to iterate an array while modifying it?

I know you shouldn't, I kind of know why. But I mean I don't understand my own code once I am trying really to think what's going on.
So I have an array with bunch of objects. I am iterating over it and once I find an object with specific type, I remove it from the array, and add another object into the array. So something like this:
var arr = parent.allchildren() //getting all the children in array
for ele in arr{
if(ele==somethingHere){
parent.remove(ele)
parent.add(new ele) //add new child into child array
}
}
If I have an array of 1,2,3,4,5, and I remove 3 and add a 6 while iterating, the actual array would be 1,2,4,5,6 but the array I am iterating would still be 1,2,3,4,5.
Which I think it would be fine, because at the end I still get what I want, which removed the element and added the element I need. However modifying the list while iterating it is bad and you shouldn't do that, but for my case I think it does what I need. What could be the potential issue in my case that I can't see?
One thing you may want to think about doing is making all of the changes at the end of the iteration. Instead of making the changes one by one, record the changes you want to make while iterating, and then actually make those changes once your loop is finished.
For example, you could make an array of elements to remove, and an array of elements to add.
//Our array where we record what we want to add
var elementsToAdd = [Any]()
//Our array of what elements we want to remove. We record the index at
//which we want to remove the element from the array
var indexesToRemoveAt = [Int]()
//Getting all the children in array
var arr = parent.allchildren()
//Enumerating an array allows us to access the index at which that
//element occurs. For example, the first element's index would be 0,
//the second element's index would be 1, the third would be 2, and so
//on
for (index,ele) in arr.enumerated() {
if(ele == somethingHere) {
indexesToRemoveAt.append(index)
elementsToAdd.append(newEle)
}
}
//Now that we have recorded the changes we want to make, we could make
//all of the changes at once
arr.remove(at: indexesToRemoveAt)
arr.append(contentsOf: elementsToAdd)
Note that removing array elements at multiple indexes would require the following extension to Array. If you wanted to avoid creating this extension, you could always just loop through the array of indexes and tell the array to remove at each individual index. All this extension function is really doing is looping through the indexes, and removing the array element at said index.
Array extension to remove elements at multiple indexes:
extension Array {
//Allows us to remove at multiple indexes instead of just one
mutating func remove(at indexes: [Int]) {
for index in indexes.sorted(by: >) {
if index <= count-1 {
remove(at: index)
}
}
}
}
I just tested in a playground with the following code:
var arr = ["hi", "bye", "guy", "fry", "sky"]
for a in arr {
if arr.count >= 3 {
arr.remove(at: 2)
}
print(a)
}
print(arr)
This prints:
hi
bye
guy
fry
sky
["hi", "bye"]
So it looks like when you use a for-in loop in Swift, the array is copied and changes you make to it will not affect the array you are iterating over. To answer your question, as long as you understand that this is the behavior, there's nothing wrong with doing this.

Why does this simple array access not work in Swift?

var word = "morning"
var arr = Array(word)
for s in 0...word.count {
print(arr[s])
}
This will not print. Of course, if I substitute a number for s, the code works fine.
Why will it not accept a variable in the array access braces? Is this peculiar to Swift?
I've spent a long time trying to figure this out, and it's nothing to do with s being optional.
Anyone understand this?
you are using inclusive range ... instead of ..<, so s goes from 0 to 7, not 0 to 6.
However, in arr the index goes from 0 to 6 because there are 7 characters.
Thus, when the program tries to access arr[7], it throws an index out of range error.
If you were coding on Xcode, the debugger would have told you that there is no arr[7].
As for the code, here is a better way to print every item in arr than using an index counter:
var word = "morning"
var arr = Array(word)
for s in arr {
print(s)
}
This is called a "foreach loop", for each item in arr, it assigns it to s, performs the code in the loop, and moves on to the next item, assigns it to s, and so on.
When you have to access every element in an array or a collection, foreach loop is generally considered to be a more elegant way to do so, unless you need to store the index of a certain item during the loop, in which case the only option is the range-based for loop (which you are using).
Happy coding!
When I run it, it prints the array then throws the error Fatal error: Index out of range. To fix this, change the for loop to:
for s in 0..<word.count {
print(arr[s])
}
try this
when you use a word to recognize
size of Array your Array index start as 0 so array last index must be equal with your (word.count - 1)
var word = "morning"
var arr = Array(word)
for s in 0...(word.count-1) {
print(arr[s])
}
Basically avoid index based for loops as much as possible.
To print each character of a string simply use
var word = "morning"
for s in word { // in Swift 3 word.characters
print(s)
}
To solve the index issue you have to use the half-open range operator ..< since indexes are zero-based.

Checking if an index exists in a non-optional Array

I have this array:
var currentTouches = [UITouch]()
At any point, it may contain 0-5 UITouches. I want to check each index and do something with the content if it exists.
But I cannot find a way to check without getting an error. The problem seems to be, that UITouch isn't an optional, so I can't just ask if it is nil.
What do I do? I tried making it an optional, but that makes much of my other code unusual. Surely there must be a simple solution.
The valid indices of currentTouches are simply currentTouches.indices. So to check if an index i is valid, you could check if currentTouches.indices.contains(i). You could also check if i < currentTouches.count (assuming you already know that i >= 0).
An easier way of doing that would be to just loop on the valid indices and handle each in turn:
for index in currentTouches.indices {
// handle value at index
}
Or if you don't care about the indices:
for touch in currentTouches {
// handle touch
}
Even better is to use enumerated() which gives you a tuple containing the index and value:
for (index, touch) in currentTouches.enumerated() {
// handle touch at index
}

Actionscript 3 Search for string in array

I have a problem with searching for strings in an array. I want to search for one word and if it exists, I want to trace the position of the string in the array.
I believe it should be something like this:
if (myArray contains "11111111") {
trace("*position*")
} else {
trace("cant find it");
}
What kind of syntax are you using there and have you even checked the documentation of the Array class? That should be the first thing you check always, as there is a pretty straightforward method for it:
var arr:Array = ["1111", "2222", "3333"];
trace(arr.indexOf("3333")); //traces the index: 2

Resources