-4

I have a itemArray, and I need remove all item index that contained in another array indexArray.

list = ["1", "2", "3", "4", "5"]
rows = [2, 4]

for i in rows {
   list.remove(at: i)
}

I do want to remove "3", "5", but the above code will be crash. I need set rows = [4, 2], remove to worked well

Prasad
  • 3,462
  • 1
  • 23
  • 28
symbool
  • 1,077
  • 1
  • 5
  • 4

1 Answers1

0

Your code is crashing because after you're delete the element at index-2, the elements count in array is reduced. Hence, when deleting element at index-5, it results in runtime exception "Index out of bounds".

So, you need to sort the rows array in decreasing order and then delete the elements from list one by one, i.e.

var list = ["1", "2", "3", "4", "5"]
var rows = [2, 4]
rows.sorted(by: >).forEach({ list.remove(at: $0) })
print(list) //["1", "2", "4"]
PGDev
  • 23,751
  • 6
  • 34
  • 88
  • You can simplify it with `sorted(by: >)` – Alexander Aug 08 '19 at 10:30
  • Is the issue resolved? – PGDev Aug 14 '19 at 16:26
  • Yep, looks good. I would also omit the https://www.google.com/search?client=safari&rls=en&q=parentheses&ie=UTF-8&oe=UTF-8 and use trailing closure syntax: `.forEach { list.remove(at: $0) }`. Optionally, you could use partial method application instead: `.forEach(list.remove(at:))` – Alexander Aug 14 '19 at 16:51