Yus*_*f X 5 dictionary-comprehension swift
其他语言(如Python)允许您使用字典理解来从数组中创建一个字典,但我还没有弄清楚如何在Swift中执行此操作.我以为我可以使用这样的东西,但它不能编译:
let x = ["a","b","c"]
let y = x.map( { ($0:"x") })
// expected y to be ["a":"x", "b":"x", "c":"x"]
Run Code Online (Sandbox Code Playgroud)
在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
}
Run Code Online (Sandbox Code Playgroud)
这将生成字典
["a": "this is the value for a",
"b": "this is the value for b",
"c": "this is the value for c"]
Run Code Online (Sandbox Code Playgroud)
一些解释:第一个参数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
}
Run Code Online (Sandbox Code Playgroud)
调用该函数看起来像这样.
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)")
}
Run Code Online (Sandbox Code Playgroud)
更新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
}
}
Run Code Online (Sandbox Code Playgroud)
调用上面的内容就像这样.
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)")
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
727 次 |
最近记录: |