kev.a
kev.a

Reputation: 33

Search an object in an array with a start index

I loop through an Array and every time a found an object with the category equal to 1 I want to check if there is another object in the rest of the array with this category. I wrote this method

func getNextIndex(startIndex:Int , t : [Client]) -> Int{
        var index = startIndex
        while(index < t.count && Int(t[index].category!) != 1){
            index += 1
        }
        if(t[index].category == 1){
            return index
        }else{
            return -1
        }

    }

This return always the same index I use to call the method. If I call it with index+1 the app crashes in the line if(t[index].category == 1)

Upvotes: 0

Views: 94

Answers (2)

Duncan
Duncan

Reputation: 527

The behavior you describe is exactly what one would expect from this code.

When you fall out of your "while" loop, either you've found another entry or index has passed the end of the array. The latter case is what is causing your crash.

There are many ways to code this, but to keep your code mostly the same, after the loop, simply test if index is less than t.count. If it is, you have found what you are looking for, return index. If not, then you have gone all the way through the loop without finding what you are looking for, so return -1.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

Loop condition ends the iteration in two situations:

  • When t[index].category is 1 - this is the situation that you are looking for, and your code is handling it.
  • When index reaches the end of the array - this is the situation when the desired item is not found; you code does not handle this condition, that's why your app crashes.

To fix this, and also to look for the item after the current index, change the code as follows:

func getNextIndex(startIndex:Int , t : [Client]) -> Int {
    var index = startIndex
    while(index < t.count && Int(t[index].category!) != 1){
        index += 1
    }
    if index == t.count {
        return -1
    }
    // Otherwise, category is 1. Continue searching
    while(index < t.count && Int(t[index].category!) != 1){
        index += 1
    }
    return index != t.count ? index : -1
}

Upvotes: 1

Related Questions