Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge two arrays into a dictionary?

Tags:

I have 2 arrays:

    var identic = [String]()     var linef = [String]() 

I've appended them with data. Now for usability purposes my goal is to combine them all into a dictionary with the following structure

FullStack = ["identic 1st value":"linef first value", "identic 2nd value":"linef 2nd value"] 

I've been browsing around the net and couldnt find a viable solution to this.

Any ideas are greatly appreciated.

Thank you!

like image 252
David Robertson Avatar asked Aug 21 '15 12:08

David Robertson


People also ask

Can an array be in a dictionary?

A dictionary's item is a value that is unambiguously associated with a unique key and the key is used to retrieve the item. The key can be of any type except a variant or an array (but generally it is a string or still an integer). The item can be of any type: integer, real, string, variant, object and so on.


1 Answers

Starting with Xcode 9.0, you can simply do:

var identic = [String]() var linef = [String]()  // Add data...  let fullStack = Dictionary(uniqueKeysWithValues: zip(identic, linef)) 

If your keys are not guaranteed to be unique, use this instead:

let fullStack =     Dictionary(zip(identic, linef), uniquingKeysWith: { (first, _) in first }) 

or

let fullStack =     Dictionary(zip(identic, linef), uniquingKeysWith: { (_, last) in last }) 

Documentation:

  • https://developer.apple.com/documentation/swift/dictionary/3127165-init

  • https://developer.apple.com/documentation/swift/dictionary/3127161-init

like image 188
Matusalem Marques Avatar answered Oct 27 '22 00:10

Matusalem Marques