indexesOfObjectsPassingTest replacement for Swift Array

What is the best replacement for indexesOfObjectsPassingTest when using Swift arrays?

Maybe something like…

extension Array {
  public func indexesOf(@noescape predicate: Generator.Element throws -> Bool) rethrows -> [Int]? {
  let indexes = try self.enumerate()
  .filter {try predicate($0.element)}
  .map {$0.index}

  return indexes.count > 0 ? indexes : nil
  }
}
[1, 2, 3, 4].indexesOf {$0 > 2}

OK I'll try that. Now…care to explain how it works? 😀 I'm still learning the Swift Standard Library functions and map/slice/etc... are ones I haven't gotten to yet. I'll try to Google the parts I don't yet know.

I hope this may be some help of you.


A simplified version (cannot use `throws` closure):

extension Array {
    public func indexesOf(@noescape predicate: Generator.Element -> Bool) -> [Int] {
        return self.indices.filter {predicate(self[$0])}
    }
}


Another implementation without using filter:

extension Array {
    public func anotherIndexesOf(@noescape predicate: Generator.Element -> Bool) -> [Int] {
        var result: [Int] = []
        for index in self.indices {
            if predicate(self[index]) {
                result.append(index)
            }
        }
        return result
    }
}

What is the best replacement for indexesOfObjectsPassingTest when using Swift arrays?

You’ve got some good replies here but I fear you might be asking the wrong question.

-indexesOfObjectsPassingTest:
works well in an NSArray world because NSArray supports other handy-dandy methods like
-objectsAtIndexes:
,
-replaceObjectsAtIndexes:withObjects:
, and so on. Swift arrays don’t support those, but they have lots of other neat-o features. If you describe more about your high-level goal, you may find a more Swift-y solution.

Share and Enjoy

Quinn "The Eskimo!"
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
indexesOfObjectsPassingTest replacement for Swift Array
 
 
Q