Swift 字典理解

标签 swift dictionary-comprehension

其他语言(例如 Python)允许您使用字典推导式从数组生成字典,但我还不知道如何在 Swift 中执行此操作。我以为我可以使用这样的东西,但它无法编译:

let x = ["a","b","c"]
let y = x.map( { ($0:"x") })
// expected y to be ["a":"x", "b":"x", "c":"x"]

在 swift 中从数组生成字典的正确方法是什么?

最佳答案

map 方法只是将数组的每个元素转换为一个新元素。然而,结果仍然是一个数组。要将数组转换为字典,您可以使用 reduce 方法。

let x = ["a","b","c"]
let y = x.reduce([String: String]()) { (var dict, arrayElem) in
    dict[arrayElem] = "this is the value for \(arrayElem)"
    return dict
}

这将生成字典

["a": "this is the value for a",
 "b": "this is the value for b",
 "c": "this is the value for c"]

一些解释:reduce 的第一个参数是初始值,在本例中是空字典 [String: String]()reduce 的第二个参数是一个回调,用于将数组的每个元素组合成当前值。在这种情况下,当前值是字典,我们在其中为每个数组元素定义一个新的键和值。修改后的字典也需要在回调中返回。


更新:由于 reduce 方法对大型数组的内存占用很大(请参阅评论),您还可以定义一个类似于以下代码段的自定义理解函数。

func dictionaryComprehension<T,K,V>(array: [T], map: (T) -> (key: K, value: V)?) -> [K: V] {
    var dict = [K: V]()
    for element in array {
        if let (key, value) = map(element) {
            dict[key] = value
        }
    }
    return dict
}

调用该函数看起来像这样。

let x = ["a","b","c"]
let y = dictionaryComprehension(x) { (element) -> (key: String, value: String)? in
    return (key: element, value: "this is the value for \(element)")
}

更新 2:除了自定义函数,您还可以在 Array 上定义一个扩展,这将使代码更易于重用。

extension Array {
    func toDict<K,V>(map: (T) -> (key: K, value: V)?) -> [K: V] {
        var dict = [K: V]()
        for element in self {
            if let (key, value) = map(element) {
                dict[key] = value
            }
        }
        return dict
    }
}

调用上面的代码看起来像这样。

let x = ["a","b","c"]
let y = x.toDict { (element) -> (key: String, value: String)? in
    return (key: element, value: "this is the value for \(element)")
}

关于Swift 字典理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022162/

相关文章:

Swift 导航栏按钮和标题不出现

来自 dict 理解引用子类的 Python 类变量

python - 如何将元组列表转换为以索引为键的字典

swift - 声明作为子类并符合 Swift 4 协议(protocol)的元类型

ios - 无法在 WKWebView 中加载网页

ios - swift - fatal error : unexpectedly found nil while unwrapping an Optional value (lldb)

python - 如何可读且有效地创建一个可迭代组合字典,并以其索引的元组为键?

ios - 如何为具有命名参数的完成处理程序创建类型别名

python - 返回不包括指定键的字典副本

python - 从嵌套列表创建字典