Let’s discuss count and isEmpty property in Swift.
We can use various built-in properties that help us to get information about sets or arrays in Swift!
For example, we use .count
to determine the number of elements in a set:
setName.count
We learned how to use .count
with arrays. .count
returns an Int
value representing the number of values stored in a specified set.
For example, we make a set to store the items we found in our refrigerator:
var refrigerator: Set = ["coldDrink", "Fruits", "Vegetables"];
Then we could use .count
to determine how many items are in our refrigerator
:
print("I have \(refrigerator.count) items in my Refrigerator!");
// Prints: I have 3 items in my Refrigerator!
If we want to know if our set is empty, we can use the .isEmpty
property to see if it contains any values.
setName.isEmpty
true
if no values are found in the set.false
.Let’s check set music
and place music.isEmpty
in the conditional of an if
statement to see if it’s empty:
var music = Set<String>();
if music.isEmpty {
print("Let's download some music!");
}
// Prints: Let's download some music!
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.