We used Swift’s built-in properties
.count on arrays and sets. We can use these properties on dictionaries as well, because they are a collection type. To Inspect a Dictionary in Swift we use
.isEmpty property, returns a boolean value indicating whether or not a dictionary is empty:
trueif the dictionary is empty.
falseif there are elements in the dictionary.
.count is another useful property to use with dictionaries. The number of elements in a dictionary is represented by this property, which returns an integer:
Take a look at how these properties work in practice:
// Declare an empty dictionary var student: [Int: String] = [:]; // Check if dictionary is empty print(student.isEmpty); // Prints: true // Add a value to the dictionary student = "Alex Ward"; // Check if dictionary is empty print(student.isEmpty) // Prints: false // Print how many elements are in dictionary print(student.count) // Prints: 1
Here are some useful tools to help you along your journey!
Setting up an IDE (Integrated Development Environment) can be difficult for beginners. The Online Compiler will enable you to run your code inside your browser without the need to install an IDE. If you need a more detailed explanation of a specific topic, the best place to find answers is in the Official Documentation.