Swift数组中的RemoveAtIndex崩溃 [英] RemoveAtIndex crash from swift array

查看:290
本文介绍了Swift数组中的RemoveAtIndex崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字母数组,想要将字符与字母进行匹配,然后对该字母进行某些操作(在这种情况下,将其变为黄色),然后从字符数组中删除该匹配的字符.

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 character from the characters array.

如果我有一个word1如"recruitment"和specialLetters如"ment",则removeAtIndex可以正常工作,但是在下面的示例中,它在[ness]中包含2 s,我会遇到此崩溃: >

If I have a word1 like "recruitment" and specialLetters like "ment" the removeAtIndex works fine, but in the below example which includes 2 s's in [ness] I get this crash:

严重错误:数组索引超出范围

fatal error: Array index out of range

在这里阅读其他文章表明,使用时从数组中删除项目是危险的,但是用一些单词而不是其他单词如何工作就可以了?我以为枚举数组只会给每个字母一个索引?还有关于如何修复它以使其适用于所有类型字符的建议?

Reading other posts on here suggest it is dangerous to remove items from an array when in use, but how come it works ok with some words and not others? I thought enumerating the array would only give each letter one index? And any suggestion on how to fix it so it works for all types of characters?

var letters = Array(word1) // [r,a,n,d,o,m,n,e,s,s]
var characters = Array(specialLetters) // [n,e,s,s]

// delete the special letters
for (index, element) in enumerate(characters) {
    if letter == element {
        tile.letterLabel.textColor = UIColor.yellowColor()

        // remove that character from the array so can't be matched twice
        characters.removeAtIndex(index)
    }
}

推荐答案

是的,在枚举时修改数组中的项数非常危险.

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

假设您有一个包含三个项目的数组,范围是0...2.在第一次迭代中,删除第一项,然后array [2]现在是array [1],索引2处不再有任何项.

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.

当然,Swift具有更可靠的功能来完成此任务,如其他人所提到的,因此在这种情况下不需要使用enumerate.

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.

这篇关于Swift数组中的RemoveAtIndex崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆