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 function count on the dictionary.

The syntax to count the elements in a dictionary is given below.

dictionary_name.count

The count function returns a number representing the size of the dictionary.

Example 1 – Get the 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

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 the size of an empty Swift Dictionary

In this example, we will create an empty dictionary and find its size using count function. The count function should return 0.

main.swift

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 function.