斯威夫特在枚举期间从阵列中删除? [英] Removing from array during enumeration in Swift?

查看:182
本文介绍了斯威夫特在枚举期间从阵列中删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在斯威夫特数组枚举,并删除某些项目。我不知道这是否是安全的话,如果没有,我应该如何实现这一目标。

目前,我会做这样的:

 为(索引,ASTRING:字符串)在历数(阵列){
    //某些字符串...
    array.removeAtIndex(指数)
}


解决方案

在斯威夫特2这是很容易的使用枚举逆转

  VAR一个= [1,2,3,4,5,6]
在a.enumerate()(I,NUM)。反向(){
    a.removeAtIndex㈠
}
打印(一)

在这里看到我的swiftstub:
http://swiftstub.com/944024718/?v=beta

I want to enumerate through an array in Swift, and remove certain items. I'm wondering if this is safe to do, and if not, how I'm supposed to achieve this.

Currently, I'd be doing this:

for (index, aString: String) in enumerate(array) {
    //Some of the strings...
    array.removeAtIndex(index)
}

解决方案

In Swift 2 this is quite easy using enumerate and reverse.

var a = [1,2,3,4,5,6]
for (i,num) in a.enumerate().reverse() {
    a.removeAtIndex(i)
}
print(a)

See my swiftstub here: http://swiftstub.com/944024718/?v=beta

这篇关于斯威夫特在枚举期间从阵列中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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