RodolfoAntonici RodolfoAntonici - 8 months ago 28
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)


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)" }