Anyone know an elegant way to return an array of index values from an array of Bools where the values are true. E.g:
任何人都知道一种优雅的方法来返回值为true的Bools数组中的索引值数组。例如:
let boolArray = [true, true, false, true]
This should return:
这应该返回:
[0,1,3]
1 个解决方案
#1
7
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]
#1
7
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]