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
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…