在Swift中将字典值转换为其他类型

时间:2016-03-10 11:02:48

标签: swift dictionary

我有一本字典。我想通过它并将值转换为不同的类型。 .map{ }将是完美的,除非这是一个字典而不是数组。所以,我在堆栈溢出上找到了一个mapPairs函数,它应该适用于字典。不幸的是我收到转换错误。

extension Dictionary {
    //    Since Dictionary conforms to CollectionType, and its Element typealias is a (key, value) tuple, that means you ought to be able to do something like this:
    //
    //    result = dict.map { (key, value) in (key, value.uppercaseString) }
    //
    //    However, that won't actually assign to a Dictionary-typed variable. THE MAP METHOD IS DEFINED TO ALWAYS RETURN AN ARRAY (THE [T]), even for other types like dictionaries. If you write a constructor that'll turn an array of two-tuples into a Dictionary and all will be right with the world:
    //  Now you can do this:
    //    result = Dictionary(dict.map { (key, value) in (key, value.uppercaseString) })
    //
    init(_ pairs: [Element]) {
        self.init()
        for (k, v) in pairs {
            self[k] = v
        }
    }

    //    You may even want to write a Dictionary-specific version of map just to avoid explicitly calling the constructor. Here I've also included an implementation of filter:
    //    let testarr = ["foo" : 1, "bar" : 2]
    //    let result = testarr.mapPairs { (key, value) in (key, value * 2) }
    //    result["bar"]
    func mapPairs<OutKey: Hashable, OutValue>(@noescape transform: Element throws -> (OutKey, OutValue)) rethrows -> [OutKey: OutValue] {
        return Dictionary<OutKey, OutValue>(try map(transform))
    }

}

var dict1 = ["a" : 1, "b": 2, "c": 3]

let convertedDict: [String: String] = dict1.mapPairs { // ERROR: cannot convert value of type '_ -> (String, Int)' to expected argument type '(String, Int) -> (String, String)'
    element -> (String, Int) in
        element[0] = String(element.1)
        return element
}

4 个答案:

答案 0 :(得分:2)

如果您想将[String: Int]的词组更改为[String: String],您几乎可以像我之前的回答一样:

let dict1 = ["a" : 1, "b": 2, "c": 3]
var dict2 = [String: String]()

dict1.forEach { dict2[$0.0] = String($0.1) }

print("\(dict2.dynamicType): \(dict2)")

输出:

Dictionary<String, String>: ["b": "2", "a": "1", "c": "3"]

答案 1 :(得分:2)

作为方法块给出的示例,您应该使用mapPairs,如下所示:

let convertedDict: [String: String] = dict1.mapPairs { (key, value) in
    (key, String(value))
}

注意,由于Swift支持隐式推理,因此您不需要显式return

答案 2 :(得分:0)

在Swift 5和更高版本中:

let originalDict: [TypeA: TypeB] = /* */
let convertedDict: [TypeA: TypeC] = originalDict.mapValues { /* conversion here */ }

示例:

let integerDict: [String: Int] = ["a": 1, "b": 2]
let doubleDict: [String: Double] = integerDict.mapValues(Double.init)

print(doubleDict) // ["a": 1.0, "b": 2.0]

答案 3 :(得分:0)

我不知道这是否有帮助,但是自Swift 4.2起,有一个名为mapValues(_:)https://developer.apple.com/documentation/swift/dictionary/2995348-mapvalues)的新运算符,它将把您要寻找的结果转换为:

let convertedDict = dict1.mapValues { String($0) }