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

6
  • Iterate in reverse to avoid this problem. Or filter the array instead of using a for loop. Commented May 1, 2018 at 16:08
  • 1
    Use filter: stackoverflow.com/q/35101099/1187415, stackoverflow.com/q/28323848/1187415 Commented May 1, 2018 at 16:08
  • @rmaddy how can I filter my array to get out all the objects that have a .isSquadPlaylist = true Commented May 1, 2018 at 16:15
  • Update your question with relevant code fully demonstrating your issue. Commented May 1, 2018 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 instance (which is a kind of Sequence). Further changes to count won't effect the for loop, because it's iterating this existing sequence. Commented May 1, 2018 at 18:15

1 Answer 1

1

Use filter:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

See also the answer by @Krunal here: stackoverflow.com/questions/39974838/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.