首先,我不需要匹配的第一个索引。我需要所有这些。
示例要清楚:
let a = [1,5,2,6,7,3,4]
let indices = a.operatorINeed { $0 > 4 } // [1,3,4]
提前致谢
您可以结合使用enumerated
和compactMap
来实现此目的:
let indices = a.enumerated().compactMap { $1 > 4 ? $0 : nil }
我从这个启发。[https://stackoverflow.com/a/41256191/3950721]
我创建了一个扩展来传递谓词作为所有类型的参数筛选。
extension Array where Element: Comparable {
func indexes(predicate: (Element) -> Bool) -> [Int] {
var result: [Int] = []
for (index, element) in enumerated() {
if predicate(element) {
result.append(index)
}
}
return result
}
}