Swift等同于`[NSDictionary initWithObjects:forKeys:]` [英] Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`
问题描述
NSArray * keys = @ [@one,@two ,@三];
NSArray * values = @ [@ 1,@ 2,@ 3];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:值为Keys:keys];
当然,我可以通过两个数组迭代一个计数器,使用 var dict:[String:Int]
并逐步添加内容。但这似乎不是一个好的解决方案。使用 zip
和枚举
可能是更好的方法来同时迭代两者。然而,这种方法意味着拥有一个可变字典,而不是一个不可变的字典。
let keys = [one,two three]
let values = [1,2,3]
// ???
let dict:[String:Int] = [one:1,two:2,three:3] //预期结果
使用 zip
和 reduce
:
let dict = zip(keys,values).reduce([String: Int]()){var d = $ 0; d [$ 1.0] = $ 1.1;返回d}
您可以缩短 reduce
通过为字典
和元组
+ >:
func +< K,V>(lhs:[K:V],rhs:(K,V) ) - > [K:V] {
var result = lhs
result [rhs.0] = rhs.1
return result
}
let dict = zip(键,值).reduce([String:Int](),combine:+)
Is there an equivalent for Swift's native Dictionary
to [NSDictionary initWithObjects: forKeys:]
?
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];
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
A one-liner, using zip
and reduce
:
let dict = zip(keys, values).reduce([String:Int]()){ var d = $0; d[$1.0] = $1.1; return d }
You can shorten the reduce
expression by defining the +
operator for a Dictionary
and a tuple
:
func +<K,V>(lhs: [K:V], rhs: (K, V)) -> [K:V] {
var result = lhs
result[rhs.0] = rhs.1
return result
}
let dict = zip(keys, values).reduce([String:Int](), combine: +)
这篇关于Swift等同于`[NSDictionary initWithObjects:forKeys:]`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!