Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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.
Syntax
func functionName(dict:[DataType:DataType]){
// Body
}
So this is how you can define a function which takes a dictionary as its argument.
functionName(dict:DictionayName)
This is how you can pass a dictionary as a function argument.
Dict.last
Here Dict is the name of the dictionary from which you want to get the last key-value pair.
Algorithm
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.
Example
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)
Output
5:- 2783 3:- 1887 1:- 1990 4:- 1999
Conclusion
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.
