arrays - 查找数组中所有元素实例的索引

标签 arrays swift

老实说,这个问题很简单。有没有办法在不循环遍历的情况下快速查找数组中所有出现的元素?似乎所有内置方法都只返回第一次出现的索引,而不是全部。

如果有一个返回索引数组的 index(where:) 风格的方法会很不错。有什么想法吗?

在此先感谢您的任何意见!

编辑:

谢谢大家的回复!看起来我应该更清楚这一点。我目前这样做的方式是一个看起来与下面发布的 one matt 非常相似的扩展。我知道执行此操作的任何方法都必须在引擎盖下循环遍历数组,我更想知道是否有一个我不知道的语言中埋藏的内置方法。这似乎是某些人通常想做的事情。看起来扩展程序就在这里!

最佳答案

Is there a way to find all occurrences of an element in an array in swift without looping through it

不,显然不是。任何魔力都无法一下子扫视整个阵法。

不必进行循环,但无论您做什么,您至少都必须要求 Swift 为您 遍历数组。 有人——无论是你还是 Swift——必须循环。

例如,这可能看起来优雅而简洁:

    let arr = [1, 2, 3, 1, 0, 1, 2, 2, 3, 1, 1, 2]
    let target = 1
    let indices = arr.enumerated().reduce(into: []) {
        if $1.1 == target {$0.append($1.0)}
    }
    // indices is [0, 3, 5, 9, 10]

...但是猜猜reduce 的作用是什么?它循环。


顺便说一句,我建议将这种东西封装为通用扩展:

extension Collection where Element : Equatable {
    func allIndices(of target:Element) -> [Int] {
        let indices = self.enumerated().reduce(into: [Int]()) {
            if $1.1 == target {$0.append($1.0)}
        }
        return indices
    }
}

这样,只要你想要所有的索引,你就可以这样说:

let arr = [1, 2, 3, 1, 0, 1, 2, 2, 3, 1, 1, 2]
let indices = arr.allIndices(of: 1)

关于arrays - 查找数组中所有元素实例的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49845375/

相关文章:

javascript - 使用另一个日期数组删除日期数组

python - 这对缓冲区操作更有效 : python strings or array()

ios - 尝试根据设备的角度旋转图像

ios - 如何在 Swift 4 中更改谷歌地图的簇颜色

ios - Swift:需要将使用按钮存储的数据移动到另一个 View Controller

ios - Firebase 权限 : Sign up with username and password

c++ - 数组与 vector ,内存布局

javascript - 随机唯一数字的大小数组

javascript - 使用拼接删除数组元素后,Google Chrome 控制台未显示正确的数据

cocoa - Swift 应用程序未在 Mavericks 上启动