RemoveAtIndex crash from swift array

后端 未结 5 733
半阙折子戏
半阙折子戏 2021-01-25 20:43

I have an array of letters, and want to match the characters against the letters and then do something to that letter (in this case turn it yellow) and then remove that matched

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-25 21:22

    Yes it is very dangerous to modify the number of items in an array while being enumerated.

    Imagine you have an array of three items, the range is 0...2. In the first iteration you delete the first item, then array[2] is now array[1] and there is no item at index 2 any more.

    Either you enumerate the array backwards, so the index of the removed item is always equal to or higher than the current index or you use a variable to collect the indexes to be deleted and delete the characters by range.

    Of course Swift has more reliable functions to accomplish this task as mentioned by the others therefore it's not needed to use enumerate In this case.

提交回复
热议问题