Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

ios - Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can simply use the Swift equivalent of initWithObjects:forKeys:

let keys = ["one", "two", "three"]
let values = [1, 2, 3]
var dict = NSDictionary.init(objects: values, forKeys: keys)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...