Swift-如何获取数组过滤项的索引 [英] Swift - How to get indexes of filtered items of array
本文介绍了Swift-如何获取数组过滤项的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
let items: [String] = ["A", "B", "A", "C", "A", "D"]
items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]
Swift 3是否支持whatFunction(_: Element)
之类的功能?
Does Swift 3 support a function like whatFunction(_: Element)
?
如果没有,最有效的逻辑是什么?
If not, what is the most efficient logic?
推荐答案
您可以为数组创建自己的扩展名.
You can create your own extension for arrays.
extension Array where Element: Equatable {
func indexes(of element: Element) -> [Int] {
return self.enumerated().filter({ element == $0.element }).map({ $0.offset })
}
}
您可以这样简单地称呼它
You can simply call it like this
items.indexes(of: "A") // [0, 2, 4]
items.indexes(of: "B") // [1]
这篇关于Swift-如何获取数组过滤项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文