查找数组中元素的所有实例的索引 [英] Finding indices for all instances of element in array

查看:102
本文介绍了查找数组中元素的所有实例的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This question is pretty simple honestly. Is there a way to find all occurrences of an element in an array in swift without looping through it? It seems like all the built in methods only return the index of the first occurrence, not all of them.

使用index(where:)样式的方法返回索引数组会很可爱.有什么想法吗?

It would be lovely to have a index(where:) style approach that returns an array of indices. Any thoughts?

在此先感谢您的输入!

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

Thanks everyone for the replies! Looks like I should have been clearer on this. The way I'm currently doing this is an extension that looks very similar to the one matt posted below. I understand that any method for doing this will have to loop through the array under the hood, I was more wondering if there was a built in method buried in the language somewhere that I was unaware of. It just seems like something someone would commonly want to do. Looks like the extension is here to stay!

推荐答案

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

You can create your own indices method that takes a predicate as parameter:

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))]

这篇关于查找数组中元素的所有实例的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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