Swift Dictionary: join key and value into string

时间:2016-07-11 20:00:24

标签: swift dictionary syntax

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)

4 个答案:

答案 0 :(得分:14)

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 preserve the input ordering.

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

let responseString = responseParameters.map{ "\($0):\($1)" }
                                       .joinWithSeparator("+")

答案 1 :(得分:4)

A dictionary is not an ordered collection, so you'll have to sort the keys prior to accessing the "ordered version" of the key-value pairs. E.g.

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

let responseString = responseParameters
    .sort { $0.0 < $1.0 }
    .map { $0 + ":" + $1 }
    .joinWithSeparator("+")

print(responseString) // keyA:valueA+keyB:valueB+keyC:valueC

答案 2 :(得分:1)

实际上,您可以像这样使用reduce

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

let responseString = responseParameters.reduce("") { $0.isEmpty ? "\($1.key):\($1.value)" : "\($0)+\($1.key):\($1.value)" }

答案 3 :(得分:1)

更新后的快速答案5:

let responseParameters = ["keyA": "valueA", "keyB": "valueB"]
let responseString = responseParameters.map { "\($0):\($1)" }
                                   .joined(separator: "+")