Swift 3 Array,使用.remove(at:i)一次删除多个项目 [英] Swift 3 Array, remove more than one item at once, with .remove(at: i)

查看:2270
本文介绍了Swift 3 Array,使用.remove(at:i)一次删除多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从数组中删除多个项目,同时使用索引位置按照.remove(at:i)类似:

Is it possible to remove more than one item from an array, at the same time, using index locations as per .remove(at: i) kind of like:

伪代码:

myArray.remove(at: 3, 5, 8, 12)

如果是这样,这样做的语法是什么?

And if so, what's the syntax for doing this?

更新

我试过这个,它有效,但下面的答案中的扩展很多更可读,更明智,并实现与伪代码完全相同的目标。

I was trying this, it worked, but the extension in the answer below is much more readable, and sensible, and achieves the goal of one that's exactly as the pseudo code.

创建一系列位置:[3,5,8, 12]

an array of "positions" is created: [3, 5, 8, 12]

let sorted = positions.sorted(by: { $1 < $0 })
for index in sorted
{
    myArray.remove(at: index)
}


推荐答案

如果索引是连续的,可以使用 removeSubrange 方法。
例如,如果您想删除索引3到5的项目:

It's possible if the indexes are continuous using removeSubrange method. For example, if you would like to remove items at index 3 to 5:

myArray.removeSubrange(ClosedRange(uncheckedBounds: (lower: 3, upper: 5)))

对于非连续索引,我会建议删除索引较大的项目到较小的项目。除了代码可能更短之外,我无法想到在同一行中同时删除项目。您可以使用扩展方法执行此操作:

For non-continuous indexes, I would recommend remove items with larger index to smaller one. There is no benefit I could think of of removing items "at the same time" in one-liner except the code could be shorter. You can do so with an extension method:

extension Array {
  mutating func remove(at indexes: [Int]) {
    for index in indexes.sorted(by: >) {
      remove(at: index)
    }
  }
}

然后:

myArray.remove(at: [3, 5, 8, 12])

更新:使用上面的解决方案,您需要确保索引数组不包含重复索引。或者您可以避免重复,如下所示:

UPDATE: using the solution above, you would need to ensure the indexes array does not contain duplicated indexes. Or you can avoid the duplicates as below:

extension Array {
    mutating func remove(at indexes: [Int]) {
        var lastIndex: Int? = nil
        for index in indexes.sorted(by: >) {
            guard lastIndex != index else {
                continue
            }
            remove(at: index)
            lastIndex = index
        }
    }
}


var myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
myArray.remove(at: [5, 3, 5, 12]) // duplicated index 5
// result: [0, 1, 2, 4, 6, 7, 8, 9, 10, 11, 13] only 3 elements are removed

这篇关于Swift 3 Array,使用.remove(at:i)一次删除多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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