Danny Danny - 5 months ago 7
Swift Question

Return an array of index values from array of Bool where true

Anyone know an elegant way to return an array of index values from an array of Bools where the values are true. E.g:

let boolArray = [true, true, false, true]


This should return:

[0,1,3]

Answer
let boolArray = [true, true, false, true]
let trueIdxs = boolArray.enumerate().flatMap { $1 ? $0 : nil }
print(trueIdxs) // [0, 1, 3]

Alternatively (possibly more readable)

let boolArray = [true, true, false, true]
let trueIdxs = boolArray.enumerate().filter { $1 }.map { $0.0 }
print(trueIdxs) // [0, 1, 3]