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)
The Key type of the dictionary is Int , and the Value type of the dictionary is String . To create a dictionary with no key-value pairs, use an empty dictionary literal ( [:] ). Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types.
Key-Value Pairs as a Function ParameterWhen calling a function with a KeyValuePairs parameter, you can pass a Swift dictionary literal without causing a Dictionary to be created. This capability can be especially important when the order of elements in the literal is significant.
To merge two dictionaries, you can use dictionary. merge method. You may do it in two ways. The type of keys array is same as that of keyType , and the type of values array is same as that of valueType .
They are: Arrays → ordered collections of values. Dictionaries → unordered collections of key-value pairs/associations.
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("+")
Updated answer for swift 5 :
let responseParameters = ["keyA": "valueA", "keyB": "valueB"]
let responseString = responseParameters.map { "\($0):\($1)" }
.joined(separator: "+")
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
Actually, you can use reduce
like: 🙌
let responseParameters = ["keyA": "valueA", "keyB": "valueB"]
let responseString = responseParameters.reduce("") { $0.isEmpty ? "\($1.key):\($1.value)" : "\($0)+\($1.key):\($1.value)" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With