Reputation: 61
I want convert [(key: String, value: String)] in [String:String] is possible to do ? If yes how i make ? thanks
var KeyValuePair: [(key: String, value: String)] = [(key: "2017 01 04", value: "143.65"), (key: "2017 01 05", value: "140.78"), (key: "2017 01 06", value: "150.23")]
in
var dictionary: [String:String] = ["2017 01 04":"143.65", "2017 01 05":"140.78", "2017 01 06":"150.23"]
Upvotes: 3
Views: 3611
Reputation: 63321
If you are sure the the keys are unique, you can use Dictionary.init(uniqueKeysWithValues:)
:
let dict = Dictionary(uniqueKeysWithValues: keyValuePairs)
Otherwise, you can use Dictionary.init(_:uniquingKeysWith:)
instead, which allows you to specify how to handle collisions.
let dict = Dictionary(keyValuePairs, uniquingKeysWith: { previous, new in
return new //always takes the newest value for a given key
})
Upvotes: 8
Reputation: 1509
The one line functional approach would be:
let dictionary = keyValuePair.reduce([String : String]())
{ acc, item in
var output = acc
output.updateValue(item.value, forKey: item.key)
return output
}
You could also neaten things up by implementing an extension
to Dictionary
extension Dictionary
{
func appending(value: Value, key: Key) -> Dictionary
{
var mutable = self
mutable.updateValue(value, forKey: key)
return mutable
}
}
let dictionary = keyValuePair.reduce([String : String]()) { $0.appending(value: $1.value, key: $1.key) }
Upvotes: 2
Reputation: 54745
You just need to iterate through the array of tuples and set the key-value pair of your dictionary with the values of the tuple.
var keyValuePairs: [(key: String, value: String)] = [(key: "2017 01 04", value: "143.65"), (key: "2017 01 05", value: "140.78"), (key: "2017 01 06", value: "150.23")]
var dictionary = [String:String]()
keyValuePairs.forEach{
dictionary[$0.0] = $0.1
//since you have named tuples, you could also write dictionary[$0.key] = $0.value
}
print(dictionary)
Please make sure you conform to the Swift naming convention, which is lower-camelcase for variable names.
Upvotes: 8