如何根据键的值初始化过滤后的键数组?
在这种情况下,我想返回所有'true'元素,它们是:[“ red”,“ green”]
var selectedColors = [
"blue": false,
"red": true,
"yellow": false,
"green": true,
"black": false,
]
所以基本上我想做到这一点:
//PSUEDO CODE
var trueColors = selectedColours.selectKeysWhereValIsTrue()
答案 0 :(得分:4)
selectedColors.filter{ $1 }.map{ $0.key }
答案 1 :(得分:2)
尽管.filter { $1 }.keys
更具可读性(并且可能是更好的选择),但值得注意的是,您可以使用compactMap
一次完成两项操作,如果您拥有{大数据集:
let trueColors = selectedColors.compactMap { color, bool in
bool ? color : nil
}
答案 2 :(得分:1)
做
let res = Array(selectedColors.filter { $0.value }.keys) // ["red", "green"]
答案 3 :(得分:1)
let trueColors = selectedColors.filter({ $0.value }).keys