Swift – Create Dictionary from Arrays

Welcome to Swift Tutorial. In our previous tutorial, we learned to create a dictionary that is empty or with some initial (key, value) pairs. In this tutorial, we will learn how to create a Dictionary using Arrays in Swift.

Two arrays are required to create a dictionary. One array is used as keys and the other array is used as values. The size of both the arrays should be same, thus making a dictionary with size same as that of the array.

Following is the syntax to create a dictionary from two Arrays.

var array1 = [key1, key2, key3]
var array2 = [value1, value2, value3]

let myDictionary = Dictionary(uniqueKeysWithValues: zip(array1, array2))

Example 1 – Create a Swift Dictionary from Arrays

In the following example, we take two arrays. The first array is a String Array of names and the second array is an Integer Array of marks. Assuming that the names array contains unique strings that can be used as keys, the following program creates a Dictionary from the two arrays. Also, we shall print the (key, value) pairs of the dictionary.

main.swift

var names = ["Mohan", "Raghu", "John"]
var marks = [75, 82, 79]

let myDictionary = Dictionary(uniqueKeysWithValues: zip(names, marks))

for (_, key_value) in myDictionary.enumerated() {
   print("\(key_value)")
}

Output

(key: "Raghu", value: 82)
(key: "John", value: 79)
(key: "Mohan", value: 75)
ADVERTISEMENT

Conclusion

In this Swift Tutorial, we have learned to create a dictionary from two arrays of same length.