在Swift中查找数组内元素所有出现位置的索引
在Swift中获取元素所有出现位置的索引(无需手动遍历)
嗨,这个需求我太懂了!Swift标准库确实只提供了返回首个匹配索引的index(where:),但我们可以通过扩展Collection协议,实现一个风格完全一致的方法,不用手动写遍历逻辑,用标准库的高阶函数就能搞定。
实现类似index(where:)的多索引查找方法
我们可以给Collection加一个扩展方法indices(where:),它接收一个判断闭包,返回所有符合条件的索引数组:
extension Collection { func indices(where predicate: (Element) throws -> Bool) rethrows -> [Index] { // 用enumerated()把元素和对应的索引绑定,过滤符合条件的项后提取索引 return try enumerated() .filter { try predicate($0.element) } .map { $0.offset } } }
用法示例
比如我们有一个数组,要找出所有值为2的索引:
let numbers = [1, 2, 3, 2, 4, 2] let allIndices = numbers.indices(where: { $0 == 2 }) print(allIndices) // 输出: [1, 3, 5]
针对Equatable类型的简化版本
如果你的元素类型遵循Equatable(比如Int、String这些常用类型),还可以再封装一个更简洁的indices(of:)方法,不用写闭包直接传元素:
extension Collection where Element: Equatable { func indices(of element: Element) -> [Index] { return indices(where: { $0 == element }) } }
简化用法
let allIndices = numbers.indices(of: 2) print(allIndices) // 同样输出: [1, 3, 5]
为什么这不算“手动遍历”?
这里的enumerated()和高阶函数filter、map其实都是标准库帮我们处理了遍历逻辑,我们只需要关注判断条件,和使用index(where:)的体验完全一致,代码也更简洁易读,复用性拉满。
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

