Create a dictionary from an array in Swift

In this Swift programming tutorial, we are going to learn how to create a dictionary from an array in Swift.

There are many ways to create a dictionary using arrays. In this tutorial, we will learn the most simple and effective methods to achieve it. They are:

  • Using uniqueKeysWithValues initializer
  • Using a simple for loop

Let us know each of them in detail.

Using uniqueKeysWithValues initializer

The uniqueKeysWithValues initializer helps us to create a dictionary from a given key and value sequences or arrays.

We know that dictionaries store values with unique keys hence the array consisting of keys must not contain any duplicate elements to avoid runtime errors.

Syntax:

keys = [ key_1, key_2, key_3, …. key_n]
values = [value_1, value_2, value_3, …. value_n]
let myDict = Dictionary(uniqueKeysWithValues: zip(keys,values))

Here, the zip function combines keys & values arrays and helps to create a dictionary by parallelly iterating over both the arrays.

Program to create a dictionary from an array using uniqueKeysWithValues initializer:

var keysArray=[1,2,3,4]
var valuesArray=["apple","ball","cat","dog"]

let dict=Dictionary(uniqueKeysWithValues: zip(keysArray,valuesArray))
for i in dict{
    print(i)
}

Output:

(key: 2, value: "ball")
(key: 3, value: "cat")
(key: 1, value: "apple")
(key: 4, value: "dog")

In the above code, we declared two arrays of keys & values and created a dictionary using them. Since the dictionary is an unordered collection of items, we get output in an arbitrary manner when it is printed.

Using a simple for loop

We can also create the dictionary from arrays using a simple for loop. Firstly, similar to the above method, we need to have two arrays of keys and values. Then we will create an empty dictionary with suitable data types.

By parallelly iterating over elements of keys & values using the zip function in the for loop, we can add elements to our empty dictionary.

Syntax:

for (i,j) in zip(keys,values){
       dict[i] = j
}

Program to create a dictionary from an array using a for loop:

var keysArr=[1,2,3,4]
var valuesArr=["apple","ball","cat","dog"]
var dict=[Int:String]()

for (i,j) in zip(keysArr,valuesArr){
    dict[i]=j
}
print(dict)

Output:

[2: "ball", 3: "cat", 1: "apple", 4: "dog"]

In the above code, we created an empty dictionary of type Int for keys and String for values. Then we added elements of keysArr and ValuesArr using for loop. As a result, the final dictionary consists of all the elements of both the arrays as key-value pairs.

That’s it! Hope you understood how to create a dictionary from an array in Swift.

Also read,

Leave a Reply

Your email address will not be published.