Swift, how to use an array with indices to reorder another array

Viewed 237

In Swift I have an array of indices that I want to use to permute an array of values (very easy to do in Matlab), but can't figure out a simple way of doing it (using a for-loop would be easy, but I'm looking for a more efficient method).

For example:

var indices = [1,0,2]
var values = ["A","B","C"]
var permute = values[indices]
// Hoping to print: permute = ["B","A","C"]
4 Answers
var indices = [1,0,2]
var values = ["A","B","C"]
var permute = indices.map({values[$0]})
print(permute)

An alternative solution using compactMap,

let indices = [1, 0, 2]
var values = ["A", "B", "C"]
let permute = indices.compactMap({ values[$0] })
print(permute)

You can just map the keys array to the values array.

var keys = [1,0,2]
var values = ["a","b","c"]
print(keys.map({values[$0]}))
let indices = [1,0,2]
let values = ["A","B","C"]
var result: [String] = []

indices.forEach({ result.append(values[$0]) })
print(result) //["B", "A", "C"]
Related