Swift 等价于 `[NSDictionary initWithObjects: forKeys:]` [英] Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`
问题描述
Swift 的原生 Dictionary
是否有与 [NSDictionary initWithObjects: forKeys:]
等效的东西?
Is there an equivalent for Swift's native Dictionary
to [NSDictionary initWithObjects: forKeys:]
?
假设我有两个带有键和值的数组,并想将它们放入字典中.在 Objective-C 中,我会这样做:
Say I have two arrays with keys and values and want to put them in a dictionary. In Objective-C I'd do it like this:
NSArray *keys = @[@"one", @"two", @"three"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [[NSDictionary alloc] initWithObjects: values forKeys: keys];
当然,我可以使用计数器遍历两个数组,使用 var dict: [String:Int]
并逐步添加内容.但这似乎不是一个好的解决方案.使用 zip
和 enumerate
可能是同时迭代两者的更好方法.然而,这种方法意味着拥有一个可变的字典,而不是一个不可变的字典.
Of course I can iterate with a counter through both arrays, use a var dict: [String:Int]
and add stuff step by step. But that doesn't seem to be a good solution. Using zip
and enumerate
are probably better ways of iterating over both at the same time. However this approach means having a mutable dictionary, not an immutable one.
let keys = ["one", "two", "three"]
let values = [1, 2, 3]
// ???
let dict: [String:Int] = ["one":1, "two":2, "three":3] // expected result
推荐答案
从 Swift 4 开始,您可以直接从键/值对序列:
As of Swift 4 you can create a dictionary directly from a sequence of key/value pairs:
let keys = ["one", "two", "three"]
let values = [1, 2, 3]
let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))
print(dict) // ["one": 1, "three": 3, "two": 2]
这里假设所有key都不一样,否则会中止有运行时异常.
This assumes that all keys are different, otherwise it will abort with a runtime exception.
如果不能保证键是不同的,那么你可以这样做
If the keys are not guaranteed to be distinct then you can do
let keys = ["one", "two", "one"]
let values = [1, 2, 3]
let dict = Dictionary(zip(keys, values), uniquingKeysWith: { $1 })
print(dict) // ["one": 3, "two": 2]
第二个参数是一个闭包,它决定了哪个值获胜"在重复键的情况下.
The second argument is a closure which determines which value "wins" in the case of duplicate keys.
这篇关于Swift 等价于 `[NSDictionary initWithObjects: forKeys:]`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!