How can I merge two arrays into a dictionary?

A slightly different method, which doesn't require the arrays to be of the same length, because the zip function will safely handle that.

extension Dictionary {
    init(keys: [Key], values: [Value]) {
        self.init()

        for (key, value) in zip(keys, values) {
            self[key] = value
        }
    }
}

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/init(uniquekeyswithvalues:)

  • https://developer.apple.com/documentation/swift/dictionary/init(_:uniquingkeyswith:)


Use enumerated():

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

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

for (index, element) in arrayOne.enumerated() {
    dictionary[element] = arrayTwo[index]
}

The pro approach would be to use an extension:

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

        self.init()

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

Edit: enumerate()enumerated() (Swift 3 → Swift 4)