Swift Program to Print a Dictionary


In Swift, a dictionary is used to create an unordered collection in which the data is stored in the form of key-value pairs. So to print a dictionary we will use the following methods −

  • Using for-in loop

  • Using description property

Method 1: Using for-in Loop

In Swift, we can print all the key-value pairs of the given dictionary with the help of a for-in loop. The for-in loop iterates through each pair of the dictionary and displays them on the output screen.

Syntax

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

Here, the key represents the key and value represents the associated value of the current key and the dict represents the dictionary.

Example

In the following Swift program, we will print a dictionary. So we will create a dictionary with key-value pairs. Then we use a for-in loop, which iterates through each key-value pair present in the given dictionary and displays them on the output screen.

import Foundation
import Glibc

// Create a dictionary
let myDict = [123: "Cupcake", 456: "Pastry", 567: "Balls", 321: "Cream Rolls", 531: "Croissant"]

print("Key == Value")

// Printing key-value pairs using a for-in loop
for(mKey, mValue) in myDict {
   print("\(mKey) == \(mValue)")
}

Output

Key == Value
123 == Cupcake
531 == Croissant
567 == Balls
456 == Pastry
321 == Cream Rolls

Method 2: Using Description Property

We can also print a dictionary using the description property. The description property is a predefined property that returns a string which represents the content of the given dictionary.

Syntax

Dict.description

Here, it returns all the key-value pairs of the given dictionary in a string form.

Example

In the following the Swift program, we will print a dictionary. So first we create a dictionary with key-value pairs. Then we use the description property along with the print statement to display the content of the dictionary on the output screen.

import Foundation
import Glibc

// Create a dictionary
let myDict = [123: "Cupcake", 456: "Pastry", 567: "Balls", 321: "Cream Rolls", 531: "Croissant"]

// Printing key-value pairs using description property
print("Dictionary:", myDict.description)

Output

Dictionary: [567: "Balls", 456: "Pastry", 531: "Croissant", 123: "Cupcake", 321: "Cream Rolls"]

Conclusion

So this is how we can print a dictionary. Here both for-in loop and description property methods work well. Using a for-in loop we can print each key-value pair one by one also we have full control of the keys and values separately. Whereas the description property returns all the key-value pairs together in the form of a string, here we cannot access keys and values separately.

Updated on: 09-May-2023

481 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements