Swift词典理解

问题描述:

其他语言如Python让你使用字典理解从数组中做出字典,但我还没有弄清楚在Swift中如何做到这一点。我以为我可以使用这样的,但它不会编译:Swift词典理解

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

什么是产生在迅速数组的字典正确的方法是什么?

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)") 
} 
+0

请注意,这会在每个缩小步骤中创建一个新字典。如果应用于* large *数组,这可能是性能问题。 –

+0

@MartinR是因为字典是通过值传递给回调的,因为它是一个内部结构的事实? – hennes

+0

是的,确切地说。请参阅此评论:http://*.com/questions/24116271/whats-the-cleanest-way-of-applying-map-to-a-dictionary-in-swift#comment47086028_28502842。 –