Javatpoint Logo
Javatpoint Logo

Swift Iterate Arrays and Dictionaries

In programming, we often need to loop over the arrays to perform operations on an individual item of the arrays and dictionaries. However, Swift provides various ways to loop over the collections. We will discuss the ways to iterate collections in swift.

First, let's create a dictionary which we will iterate in this example.

Let's use the for-in loop to iterate over the employee dictionary.

It will print all the keys and values of the dictionary. However, we can also iterate over the reverse of the dictionary like an array.

It will print the keys and values of the dictionary in reverse order. We can also use enumerated() to get the keys, value relative to their dictionary positions.

It prints the values along with their index in the dictionary on the console.

We can also use the higher-order function like forEach() to iterate over any collection. Using forEach() is similar to the for-in loop, as shown below.

However, we cannot use jump statements like break and continue using the forEach() method. We can perform various stuff using the forEach() method. Let's consider the following example, which prints the square of the first 100 numbers on the console.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA