Open In App

Swift – Iterate Arrays and Dictionaries

Last Updated : 23 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

For iterating over arrays and dictionaries we have to use the for-in, forEach loop in Swift. Both the loops support iterating over these types of data structures like arrays, dictionaries, etc. The usage of the for-in loop over data structures is very similar to the Python for loop. Both the loops are used to run a piece of code for a certain number of times. In this article, we will learn how to iterate over arrays and dictionaries. 

Array

An array is a data structure that can hold a similar type of data where values are arranged in a continuous order. It is also called a continuous memory data structure. Arrays are used to store similar types of data. If we create an integer array, we can store only integer values. In C or Java, we have declared arrays with size, then space is allocated in memory so that we could able to store values according to allocated size. But in Swift, we can create arrays without specifying size, based on given values it will automatically declare size in the background. In other terms, it is also called dynamic memory allocation. Let us see the syntax of arrays creation.

Syntax:

let array_variable : [Data_type] = [value 1 , value 2 , . . , value n]

Iterating over arrays 

1. For-in loop: We can iterate an array using the for-in loop and access each element during the iteration.

Syntax:

for _ in array_variable {print(i)}

Example:

Swift




// Swift program to iterating over array
  
// Create an array of integer type
let arr = [ 1, 2, 3, 4, 5 ]
  
print("Array 1:")
  
// Using for-in loop
// We iterate array
for i in arr{print(i)}
  
// Create an array of string type
let arr1 = [ "karthik", "chandu", "nandu" ]
  
print("Array 2:")
  
// Using for-in loop
// We iterate array
for j in arr1{print(j)}


Output:

Array 1:
1
2
3
4
5
Array 2:
karthik
chandu
nandu

Explanation: In the first step we have created two arrays with some values. In the next step, we have iterated over the array using for loop. Inside the for loop, we have written a print statement in order to print the elements of an array. In the array, we have inserted numbers from 1 to 5. So we got 1,2,3,4,5 as output. Similarly for array 2.

2. ForEach loop: We can also iterate over an array using a forEach loop. Using the forEach loop we retrieve elements from the specified array just like the for-in loop. For that, we need to take one variable in the forEach loop. 

Syntax:

array_name.forEach{item in print(“(\(item)”)}

Example:

Swift




// Swift program to iterating over array
  
// Create an array of integer type
let arr = [ "gfg", "Geeks", "GeeksforGeeks" ]
  
print("Array Elements :")
  
// Using forEach loop
// We iterate array
arr.forEach{i in print(i)}


Output:

Array Elements :
gfg
Geeks
GeeksforGeeks

Explanation: In the first step we have created an array with some values. In the next step, we have iterated over the array using a forEach loop. Inside the forEach loop, we have written a print statement in order to print the elements of the array. In the array, we have inserted some string values and we got the respective string values as output.

Dictionary 

Dictionary is a data structure that contains data in key, value pairs. In general, a dictionary also has an index number. So using that index number we can easily find the related chapter associated with it. In a similar way here also create value along with the key. Using that key we could able to return the concerned value. While creating a dictionary we will assign keys to values. So it is easy to return value. Let us see the syntax for creating a dictionary.

Syntax:

let dict_variable = [keyt 1 : value 1 , key 2 : value 2 , . . , key n : value n]

Iterating over Dictionary

1. For in loop: As we all know that dictionary has key-value pairs. In order to iterate over a dictionary, we need to retrieve both key and value. For that, we need to take two variables in the for-in loop. 

Syntax:

for (key , value) in dict_variable{print(” \(key) = \(value) “)}

Note: In the place of = in the print function we can use anything like: , …etc. Here key and value are just variables for iterating keys and values. In the place of key and value, we can any alphabet or word.

Example:

Swift




// Swift program to iterating over dictionary
  
// Create a dictionary with key and value
let dict1 = [ 1:"karthik", 2:"chandu", 3:"nandu" ]
  
// Using for in loop 
// We iterate dictionary
for (i, j) in dict1
{
      
    // Display the key and value
    print("(\(i) : \(j))")
}


Output:

(3 : nandu)
(2 : chandu)
(1 : karthik)

Explanation: In the first step we have created a dictionary with some values. Using for loop we are accessing elements. In print statements, follow the syntax carefully. The \ beside i and j are very important and i and j should be within parenthesis. In the place of i and j we can take any valid identifier. Here i represents key and j represents value.

2. Foreach loop: We can also iterate over a dictionary using a forEach loop. Using the forEach loop we retrieve both key and value from the specified dictionary just like the for-in loop. For that, we need to take two variables in the forEach loop. 

Syntax:

dictionary_name.forEach{ key, value in print(“(\(key) : \(value))”)}

Example:

Swift




// Swift program to iterating over dictionary
  
// Create a dictionary with key and value
let dict1 = ["India": 78 , "USA" : 1 , "UAED" : 3]
  
print("Key value pairs:")
  
// Using forEach loop
// We iterate dictionary
dict1.forEach{i, j in print("(\(i) : \(j))")}


Output: 

Key value pairs:
(India : 78)
(USA : 1)
(UAED : 3)

Explanation: In the first step we have created a dictionary with key and value pairs. Using forEach loop we are accessing elements. In print statements, follow the syntax carefully. The \ beside i and j are very important and i and j should be within parenthesis. In the place of i and j we can take any valid identifier. Here i represents key and j represents value.

Note: Every time we won’t get the same output, the order changes. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads