Swift Program to Pass Dictionary as the function argument

A Swift dictionary is an unordered collection in which data is stored as key-value pairs. So to pass a dictionary as a function argument simply create a function with an argument of dictionary type and a dictionary, then pass it to the function at the time of function calling.


func functionName(dict:[DataType:DataType]){
   // Body

So this is how you can define a function which takes a dictionary as its argument.


This is how you can pass a dictionary as a function argument.


Here Dict is the name of the dictionary from which you want to get the last key-value pair.


  • Step 1 − Create a function which takes a dictionary as an argument.

  • Step 2 − Inside the function use the for-in loop to print the dictionary.

  • Step 3 − Create a dictionary.

  • Step 4 − Call the function and pass the dictionary into it as an argument.


In the following Swift program, we will pass a dictionary as the function argument. So create a function which takes a dictionary as an argument and then prints all the key-value pairs present in the dictionary. Then create a dictionary with key-value pairs and then we call the displayDictionary() function and pass the dictionary which we have already created in it and display the output.

import Foundation
import Glibc
// Function to display dictionary 
func displayDictionary(dict: [Int: Int]) {
   for (key, value) in dict {
      print("\(key):- \(value)")

// Dictionary to pass to function
let myDict = [1:1990, 3:1887, 4:1999, 5:2783]

// Call function with dictionary argument
displayDictionary(dict: myDict)


5:- 2783
3:- 1887
1:- 1990
4:- 1999


So this is how we can pass dictionary as a function argument. Using this same method you can also pass multiple dictionaries into the function. You can pass the same data type(key and value) or a different data type(key and value) dictionary in the function.

Updated on: 09-May-2023


Kickstart Your Career

Get certified by completing the course

Get Started