0

I want to avoid getting this error image of error

which is INDEX out of range. Im trying to loop through an array but when I find something I want to remove , I delete it yet the .count of the array remains the same for that iteration of the for loop , how can I fix this?

here is console when run

test i:0  count: 3
test i:1  count: 3
test i:2  count: 2

yet the to: in

    for i in stride(from: 0, to: count, by: 1)

still seems to be 3...

Can Someone show me how to filter this array or loop through and remove? as long as it works i dont care what it is

Zack117
  • 985
  • 1
  • 13
  • 28
  • Iterate in reverse to avoid this problem. Or filter the array instead of using a `for` loop. – rmaddy May 01 '18 at 16:08
  • 1
    Use filter: https://stackoverflow.com/q/35101099/1187415, https://stackoverflow.com/q/28323848/1187415 – Martin R May 01 '18 at 16:08
  • @rmaddy how can I filter my array to get out all the objects that have a .isSquadPlaylist = true – Zack117 May 01 '18 at 16:15
  • Update your question with relevant code fully demonstrating your issue. – rmaddy May 01 '18 at 16:18
  • @Zack The expression in the right side of a `for` loop is evaluated only once, prior to the first iteration. Your expression `stride(from: 0, to: count, by: 1)` will be evaluated to produce a [`StrideTo`](https://developer.apple.com/documentation/swift/strideto) instance (which is a kind of [`Sequence`](https://developer.apple.com/documentation/swift/sequence)). Further changes to `count` won't effect the `for` loop, because it's iterating this existing sequence. – Alexander May 01 '18 at 18:15
  • @Zack Similarly, the variable `i` is being assigned once at the start of every loop iteration, given the value of the result of calling `next()` on the sequence's iterator. Changing `i` won't have an effect from one iteration to the next. – Alexander May 01 '18 at 18:16

1 Answers1

1

Use filter:

let filteredImages = images.filter { $0.someproperty == whatYouWant } 

Mutating for-loops are something you want to avoid. Filtering is much safer.

Lucas van Dongen
  • 9,328
  • 7
  • 39
  • 60
  • See also the answer by @Krunal here: https://stackoverflow.com/questions/39974838/swift-3-array-remove-more-than-one-item-at-once-with-removeat-i – koen May 01 '18 at 16:31