5

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

1 Answer 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]
Sign up to request clarification or add additional context in comments.

5 Comments

Would you also please explain why you think it is elegant and best approach in your opinion that would be a great help.
@JeetendraChoudhary When we mention "elegant" in questions regarding Swift, I, among many, turn to the functional approaches available in Swift. There's numerous different approaches to accessing the indices that uphold some given condition w.r.t. the values of an array. I personally use the enumerate().flatMap or enumerate().filter{ ... }.map approach myself.
Thank you indeed very helpful, It always helps to learn from seniors like you what and why they like certain approach or method. Thank you once again.
@JeetendraChoudhary happy to help!
Awesome. Thanks @dfri

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.