Reputation: 272
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!
Upvotes: 2
Views: 1362
Reputation: 21137
Your for has two problems:
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
.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
}
Upvotes: 1
Reputation: 6114
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}
Upvotes: 0
Reputation: 9898
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)
}
}
Upvotes: 0