Swift – Dictionary Size
Welcome to Swift Tutorial. In this tutorial, we will learn how to get the size of a dictionary.
To get the length or size of a dictionary in Swift programming, use the count properly of this dictionary.
The syntax to count the elements in a dictionary is given below.
</>
Copy
dictionary_name.count
The count function returns a number representing the size of the dictionary.
Example 1 – Get Size of a Swift Dictionary
In this example, we will create a Swift Dictionary with some initial values and find its size using count function.
main.swift
</>
Copy
var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var size = myDictionary.count
print( "myDictionary size: \(size)" )
Output
myDictionary size: 3
Example 2 – Get Size of Empty Dictionary
In this example, we will create an empty dictionary and find its size using count function. Since the dictionary is empty, the count property returns 0.
main.swift
</>
Copy
var myDictionary = [String:Int]()
var size = myDictionary.count
print( "myDictionary size: \(size)" )
Output
myDictionary size: 0
Conclusion
In this Swift Tutorial, we have learned to get the length or size of a Swift Dictionary using count property.