Swift 有没有办法将KVP字典转换为字符串?

Swift 有没有办法将KVP字典转换为字符串?,swift,dictionary,Swift,Dictionary,我正在尝试将从FireStore获取的[String:Bool]变量转换为字符串 例如: var action = ["Nourishing":true, "Radiance":true] 致: “滋养,光辉” 这可能吗?如果您只想将所有键组合成一个字符串,则可以执行以下操作: var action = ["Nourishing":true, "Radiance":true, "Whatever":false] let keysAll = action.keys.joined(separato

我正在尝试将从FireStore获取的
[String:Bool]
变量转换为字符串

例如:

var action = ["Nourishing":true, "Radiance":true]
致:

“滋养,光辉”


这可能吗?

如果您只想将所有键组合成一个字符串,则可以执行以下操作:

var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysAll = action.keys.joined(separator: ", ")
print(keysAll)
var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysTrue = action.filter { $0.value }.keys.joined(separator: ", ")
print(keysTrue)
var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysTrue = action.flatMap { $0.value ? $0.key : nil }.joined(separator: ", ")
print(keysTrue)
结果:

滋养,光辉,等等

如果只需要某些键,则首先需要根据需要过滤键/值。例如,如果只需要值为
true
的键,则可以执行以下操作:

var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysAll = action.keys.joined(separator: ", ")
print(keysAll)
var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysTrue = action.filter { $0.value }.keys.joined(separator: ", ")
print(keysTrue)
var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysTrue = action.flatMap { $0.value ? $0.key : nil }.joined(separator: ", ")
print(keysTrue)
结果:

滋养的、光辉的

或者,您也可以这样做:

var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysAll = action.keys.joined(separator: ", ")
print(keysAll)
var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysTrue = action.filter { $0.value }.keys.joined(separator: ", ")
print(keysTrue)
var action = ["Nourishing":true, "Radiance":true, "Whatever":false]
let keysTrue = action.flatMap { $0.value ? $0.key : nil }.joined(separator: ", ")
print(keysTrue)

使用reduce还有更难的解决方案

 let action = ["Nourishing":true, "Radiance":true] 

     let  data =   action.reduce("") { (result, dic) -> String in
            return result.count == 0  ? (result + "\(dic.key)") :  (result + ",\(dic.key)")
      }
     print(data)

你没有数组,你有字典。是的,这是可能的。您想要所有键还是只想要值为
true
的键?谢谢!!这正是我想要的!:D