David Robertson David Robertson - 2 months ago 13
Swift Question

How can I merge two arrays into a dictionary?

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!

Answer Source

This sounds like a job for .enumerate()!

var arrayOne: [String] = []
var arrayTwo: [String] = []

var dictionary: [String: String] = [:]

for (index, element) in arrayOne.enumerate()
    dictionary[element] = arrayTwo[index]

However, if you want the pro approach, use an extension:

extension Dictionary
    public init(keys: [Key], values: [Value])
        precondition(keys.count == values.count)


        for (index, key) in keys.enumerate()
            self[key] = values[index]