We’ve used Swift’s built-in properties, .isEmpty
and .count
, to gather information about arrays and sets.
Since dictionaries are also a collection type, we can use these properties with dictionaries too!
For example, the .isEmpty
property will return a boolean value that denotes whether or not a dictionary is empty:
dictionaryName.isEmpty
- If the dictionary is empty, the expression will return
true
. - If there are elements in the dictionary, the expression will return
false
.
Another useful property to use with dictionaries is .count
. This property will return an integer that represents the number of elements contained within a dictionary:
dictionaryName.count
Let’s take a look at these properties in action:
// Declare an empty dictionary var pocketChange: [String: Int] = [:] // Check if dictionary is empty print(pocketChange.isEmpty) // Prints: true // Add a value to the dictionary pocketChange["Nickel"] = 3 // Check if dictionary is empty print(pocketChange.isEmpty) // Prints: false // Print how many elements are in dictionary print(pocketChange.count) // Prints: 1
Instructions
Create an if
statement that checks if numberOfSides
is empty using .isEmpty
.
If the dictionary is empty, print()
the statement "This dictionary has no elements in it."
.
Add an else
statement underneath the if
statement you just created.
If the dictionary is not empty, print()
the number of elements contained in numberOfSides
using the .count
property.