Assuming that
- the given indices are in increasing order, and
- all indices are valid for the array (i.e. less than the
number of elements),
then a simple map operation would work:
let indexes = [2, 4, 7]
let myArray = ["a", "b", "c", "d", "e", "f", "g", "h"]
let filtered = indexes.map { myArray[$0] }
print(filtered) //["c", "e", "h"]
Remark: In earlier Swift releases, there was a PermutationGenerator
exactly for this purpose:
let filtered = Array(PermutationGenerator(elements: myArray, indices: indexes))
print(filtered) //["c", "e", "h"]
However, this has been deprecated in Swift 2.2 and will be removed
in Swift 3. I haven't seen a Swift 3 replacement yet.
filterwould be inefficient because it would look at each value inmyArray. Consider what would happen ifmyArrayhad 100 thousand items. Your method of iterating the indexes array would loop 4 times, but filter would loop (internally) 100 thousand times.