How to store an array in the dictionary in Swift?

Suppose we have JSON data received from API. Usually, we are storing in array and dictionaries, we will see how to store array in the dictionary for the sake of arranging data in the form of instance or model.

Array in Swift:

The array is nothing but a collection of similar types of elements. which we can access by the index.

In one array we can store multiple students’ names but in the same array, we can’t store students’ student id. for storing student id we have to take another array.

For example :

Student Names Array data will be like [“Rahul”, “Sarvesh”, “Prashant”]

you can access element from array by index.

All data in the array are in the same format. The above array is a collection of String elements.

Dictionary in Swift:

Dictionary is collection of different type of element with reference key.

We can access and traverse elements from the dictionary thoroughly by key as we do it by index in the array.

Dictionary is nothing but array of key value pair.

dictionary = [key : value]

For example :

Either we can Initialise dictionary with data.

This is how we can access dictionary parameter by key.

How we can add Array in Dictionary?

let’s suppose we have array of username, this is how we can add username array in dictionary.

Print dictionary in console.

Leave a Comment