小编典典

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

swift

老实说,这个问题很简单。有没有一种方法可以快速查找数组中某个元素的所有出现而无需循环遍历它?似乎所有内置方法仅返回第一次出现的索引,而不是全部返回。

拥有index(where:)返回索引数组的样式方法将是很不错的。有什么想法吗?

预先感谢您的任何投入!

编辑:

感谢大家的回复!看来我应该对此更加清楚。我目前的操作方式是扩展,其外观与下面发布的一个哑光非常相似。我知道,任何执行此操作的方法都必须在内部遍历数组,我更想知道是否有内置方法隐藏在我不知道的语言中。好像有人通常会想做的事情。似乎该扩展程序将继续存在!


阅读 246

收藏
2020-07-07

共1个答案

小编典典

您可以创建自己的使用谓词作为参数的索引方法:

Xcode 11•Swift 5.1

extension Collection where Element: Equatable {
    func indices(of element: Element) -> [Index] { indices.filter { self[$0] == element } }
}

extension Collection {
    func indices(where isIncluded: (Element) throws -> Bool) rethrows -> [Index] { try indices.filter { try isIncluded(self[$0]) } }
}

let arr = [1, 2, 3, 1, 0, 1, 2, 2, 3, 1, 1, 2]
let search = 1

let indices = arr.indices(where: { $0 == search })
// or simply
// let indices = arr.indices { $0 == search }
print(indices)   // [0, 3, 5, 9, 10]

let indices2 = arr.indices(of:  search)
print(indices2)   // [0, 3, 5, 9, 10]

let string = "Hello World !!!"
let indices3 = string.indices(of: "o")
print(indices3)  //  [Swift.String.Index(_compoundOffset: 16, _cache: Swift.String.Index._Cache.character(1)), Swift.String.Index(_compoundOffset: 28, _cache: Swift.String.Index._Cache.character(1))]
2020-07-07