- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swift Program to Find the Size of Dictionary
This tutorial will discuss how to write swift program to find the size of dictionary.
A dictionary is used to store data in the form of key-value pair in the collation without any defined-order. Here the type of the keys are same as well as the type of the values are also same. Each key is behave like an identifier for the associate value inside the dictionary and each value has a unique key. Swift dictionary is just like the real dictionary. It loop up values according to their identifier.
Syntax
Following is the syntax for creating dictionary −
var mydict = [KeyType: ValueType]() Or var mydict : [KeyType:ValueType] = [key1:value1, key2:value2, key3:value3]
To find the size of the dictionary Swift provide a property named count. It will count all the key-value pair in the dictionary and return their total count.
Below is a demonstration of the same −
Input
Suppose our given input is −
Mydict = [1: “owl”, 2: “kiwi", 3: “frog”] Size = 3
Syntax
Following is the syntax −
dictName.count
Algorithm
Following is the algorithm −
Step 1 − Creating dictionaries with key-value pair.
Step 2 − Calculating the size of dictionary using count property.
var size1 = mydict1.count var size2 = mydict2.count
Step 3 − Print the output
Example
The following program shows how to count the size of the dictionary.
import Foundation import Glibc // Creating dictionaries var mydict1 : [Int:Int] = [2:34, 4:56, 8:98, 5:3803, 6:23] var mydict2: [Int:String] = [1:"peacock", 2:"bird", 3:"rat"] // Calculating the size of dictionary var size1 = mydict1.count var size2 = mydict2.count print("Dictionary:", mydict1) print("Size:", size1) print("Dictionary:", mydict2) print("Size:", size2)
Output
Dictionary: [5: 3803, 8: 98, 6: 23, 4: 56, 2: 34] Size: 5 Dictionary: [2: "bird", 1: "peacock", 3: "rat"] Size: 3
Here, in the above code, we have two dictionaries: mydict1 and mydict2. Now we find their size using count property.
var size1 = mydict1.count var size2 = mydict2.count
So the output is −
Dictionary: [5: 3803, 8: 98, 6: 23, 4: 56, 2: 34] Size: 5 Dictionary: [2: "bird", 1: "peacock", 3: "rat"] Size: 3