Swift等同于`[NSDictionary initWithObjects:forKeys:]` [英] Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`

查看:96
本文介绍了Swift等同于`[NSDictionary initWithObjects:forKeys:]`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个数组,包含键和值,并希望将它们放在一个字典中。在Objective-C中,我会这样做:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆