在[String:String]中转换[(key:String,value:String)]

时间:2017-08-31 15:14:51

标签: swift

我希望[String:String]中的convert [(key:String,value:String)]可以吗?如果是,我怎么做?感谢

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"]

3 个答案:

答案 0 :(得分:5)

您只需遍历元组数组并使用元组的值设置字典的键值对。

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)

请确保符合Swift命名约定,该约定是变量名称的较低值。

答案 1 :(得分:4)

Swift 4:

如果您确定这些键是唯一的,则可以使用Dicitonary.init(uniqueKeysWithValues:)

let dict = Dicitonary(uniqueKeysWithValues: keyValuePairs)

否则,您可以改为使用Dictionary.init(_:uniquingKeysWith:),这可以指定如何处理碰撞。

let dict = Dictionary(keyValuePairs, uniquingKeysWith: { previous, new in
    return new //always takes the newest value for a given key
})

答案 2 :(得分:2)

一线功能方法是:

let dictionary = keyValuePair.reduce([String : String]())
                 {  acc, item in
                    var output = acc
                    output.updateValue(item.value, forKey: item.key)
                    return output
                 }

您还可以通过实施extensionDictionary

来实现目标
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) }