Reputation: 58
How can I initialise an array of filtered keys based on the values for the keys?
In this case I want to return all the elements that are 'true' which are: ["red", "green"]
var selectedColors = [
"blue": false,
"red": true,
"yellow": false,
"green": true,
"black": false,
]
so basically I want to achieve this:
//PSUEDO CODE
var trueColors = selectedColours.selectKeysWhereValIsTrue()
Upvotes: 1
Views: 63
Reputation: 63271
Although .filter { $1 }.keys
is more readable (and probably a better go-to), it's worth noting that you can do both operations in one using compactMap
, which might get you some performance gains if you have big data sets:
let trueColors = selectedColors.compactMap { color, bool in
bool ? color : nil
}
Upvotes: 2
Reputation: 100523
Do
let res = Array(selectedColors.filter { $0.value }.keys) // ["red", "green"]
Upvotes: 1