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

筅森魡賤 提交于 2020-01-21 07:15:23

问题


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]

回答1:


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]


来源:https://stackoverflow.com/questions/38225121/return-an-array-of-index-values-from-array-of-bool-where-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!