Swift - How to get indexes of filtered items of array

Byoth picture Byoth · Aug 29, 2017 · Viewed 30k times · Source
let items: [String] = ["A", "B", "A", "C", "A", "D"]

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]

Does Swift 3 support a function like whatFunction(_: Element)?

If not, what is the most efficient logic?

Answer

vadian picture vadian · Aug 29, 2017

You can filter the indices of the array directly, it avoids the extra mapping.

let items = ["A", "B", "A", "C", "A", "D"]
let filteredIndices = items.indices.filter {items[$0] == "A"}

or as Array extension:

extension Array where Element: Equatable {

    func whatFunction(_ value :  Element) -> [Int] {
        return self.indices.filter {self[$0] == value}
    }

}

items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]

or still more generic

extension Collection where Element: Equatable {

    func whatFunction(_ value :  Element) -> [Index] {
        return self.indices.filter {self[$0] == value}
    }

}