2

While I try to create a for in loop, it gives me an error stating "cant form Range with end < start". Value of i comes 4362626962. How can I fix it?

    for i in 1...slashList.count{
        let index = slashList[i]

        if !quotaList.contains(index+1)
        {
        slashList.removeAtIndex(index)
        }
    }

Thank you in advance!

Natasha
  • 6,651
  • 3
  • 36
  • 58
slytrkmn
  • 272
  • 1
  • 4
  • 15

3 Answers3

1

Your for has two problems:

  1. If slashList.count is 0 (because slashList is empty), it would try to count from 1 to 0 adding 1 (which results in an infinite loop), that's why the compiler gives you the error start > end.
  2. if slashList.count is greater than 0 (slashList is not empty), it would use an index which is out of bounds, because you count from 1 to slashList.count, while the indexes go from 0 to slashList.count - 1

to check all indexes it should be:

for i in 0 ..< slashList.count { 
   // your code 
}

to ignore the first element (index 0) do:

for i in 1 ..< slashList.count {
   // your code 
}

for your special case, it would seem better to me to do something like:

for element in slashList {    
    if !quotaList.contains(element+1)
    {
        slashList.removeObject(element)
    }
}

You can use removeObject from this answer. If, for some reason, you also need the index, do:

for (index, element) in slashList.enumerate() {
   // your code
}
Community
  • 1
  • 1
Daniel
  • 20,420
  • 10
  • 92
  • 149
0

Try with, it should be 0.. not 1...

for i in 0..slashList.count{
    let index = slashList[i]

    if !quotaList.contains(index)
    {
    slashList.removeAtIndex(index)
    }
}
Hasya
  • 9,792
  • 4
  • 31
  • 46
0

Why you start loop from index 1 instead 0? If you really need this, you must check if slashList empty array:

if !slashList.isEmpty {
    // your code here
}

Also removing items from array you numerating is bad practice. Assume that you want to loop from 0, then there is swifty way to get what you want:

slashList = slashList.enumerate().flatMap{quotaList.contains($0.index + 1) ? $0.element : nil}
Yury
  • 6,044
  • 3
  • 19
  • 41