在 Swift 中枚举期间从数组中删除? [英] Removing from array during enumeration in Swift?

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

问题描述

我想在 Swift 中枚举数组,并删除某些项目.我想知道这样做是否安全,如果不安全,我应该如何实现这一目标.

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.

目前,我会这样做:

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

推荐答案

在 Swift 2 中,这很容易使用 enumeratereverse.

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)

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

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