RodolfoAntonici RodolfoAntonici - 1 year ago 235
Swift Question

Swift Dictionary: join key and value into string

I'm looking for a best syntax for this:

let responseParameters = ["keyA" : "valueA", "keyB" : "valueB"]
var responseString = ""
for (key, value) in responseParameters {
responseString += "\(key):\(value)"
if Array(responseParameters.keys).last != key {
responseString += "+"
//responseString: keyA:valueA+keyB:valueB

Something like an array joinWithSeparator, using a flatMap or something like that. (study purpose)

Answer Source

You can map over key/value pairs in dictionaries to convert them to an Array of Strings, then you can join those with +. But remember, dictionaries are unordered, so this will not preserver the input ordering.

let responseParameters = ["keyA" : "valueA", "keyB" : "valueB"]

let responseString ={ "\($0):\($1)" }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download