Swift Collection isEmpty and count: How and When to Use Them
Swift collections such as arrays, strings, sets, and dictionaries all let you ask two very common questions: does this collection contain anything, and how many elements does it contain? The isEmpty and count properties answer those questions. Understanding the difference between them helps you write clearer, safer, and often more efficient Swift code.
Quick answer: Use isEmpty when you only need to know whether a collection has any elements. Use count when you need the actual number of elements. In Swift, isEmpty is usually the better choice than checking count == 0 because it is clearer and expresses your intent directly.
Difficulty: Beginner
Helpful to know first: You'll understand this better if you know basic Swift syntax, how variables and constants work, and what common collection types like Array, String, Set, and Dictionary look like.
1. What Is isEmpty and count?
isEmpty and count are read-only properties provided by Swift collection types.
- isEmpty returns a Bool: true if the collection has no elements, otherwise false.
- count returns an Int: the number of elements in the collection.
- They are available on standard Swift collections such as Array, Set, Dictionary, and String.
- They solve different problems: one checks emptiness, the other measures size.
- These properties are often compared because beginners commonly write count == 0 when isEmpty is the clearer tool.
For example, if you are validating user input, checking whether a shopping cart has items, or deciding whether to display a “no results” message, these properties are often the first thing you use.
2. Why isEmpty and count Matter
These properties appear in everyday Swift code because collections are everywhere. You read from arrays, store items in dictionaries, work with strings, and loop over results from APIs. Very often, your logic depends on whether data exists or how much data exists.
Using the right property makes code easier to read:
- Use isEmpty when your question is “Are there any elements?”
- Use count when your question is “How many elements are there?”
- Avoid using count for emptiness checks unless you specifically need the number too.
This matters for readability as much as correctness. Someone reading isEmpty immediately understands your intent without mentally converting count == 0 into an emptiness check.
3. Basic Syntax or Core Idea
Checking whether a collection is empty
Use isEmpty directly on the collection.
let numbers = [1, 2, 3]
let hasNoNumbers = numbers.isEmpty
print(hasNoNumbers) // falseThis reads the property and returns a Boolean value. Because the array contains elements, the result is false.
Getting the number of elements
Use count when you need the actual size.
let numbers = [1, 2, 3]
let totalNumbers = numbers.count
print(totalNumbers) // 3This returns the total number of elements in the collection.
Using them in conditions
These properties are most useful in if statements and other control flow.
let tasks: [String] = []
if tasks.isEmpty {
print("No tasks yet.")
}
print("Task count:", tasks.count)Here, isEmpty controls the branch, and count reports the exact total.
4. Step-by-Step Examples
Example 1: Checking an empty array
This is the most common beginner example. Start with an empty array and check whether it contains anything.
let shoppingList: [String] = []
if shoppingList.isEmpty {
print("Your shopping list is empty.")
}The condition is true because the array has no elements. This is clearer than writing shoppingList.count == 0.
Example 2: Counting items in an array
When you need the total number of values, use count.
let scores = [95, 88, 76, 100]
print("There are \(scores.count) scores.")This prints the number of elements in the array, which is useful for summaries, UI labels, and reports.
Example 3: Using isEmpty with a string
String also supports these properties because strings are collections of characters.
let username = ""
if username.isEmpty {
print("Please enter a username.")
}This is useful in validation. An empty string is not the same as a missing optional value, but it often still needs special handling.
Example 4: Counting entries in a dictionary
Dictionaries use count to tell you how many key-value pairs they store.
let stock = ["Apples": 12, "Bananas": 6]
print("Items in stock dictionary: \(stock.count)")The result is 2 because there are two key-value pairs, not because the values add up to anything.
Example 5: isEmpty vs count == 0
Both of the following expressions produce the same result for normal emptiness checks, but one is preferred.
let messages: [String] = []
print(messages.isEmpty) // true
print(messages.count == 0) // trueBoth work, but isEmpty is more expressive. It says exactly what you are checking.
5. Practical Use Cases
- Show a “No results found” message when a filtered array is empty.
- Validate form fields by checking whether a string is empty before continuing.
- Display the number of notifications, files, or downloaded items with count.
- Decide whether to process API results only when a returned collection is not empty.
- Prevent index access on an empty array by checking isEmpty first.
- Report how many unique values are stored in a Set.
- Check whether a dictionary has any stored settings before loading defaults.
6. Common Mistakes
Mistake 1: Using count when you only need an emptiness check
Beginners often write count == 0 everywhere, even when the code only needs to know whether the collection is empty.
Problem: The code works, but it communicates the wrong intent. You are asking for the size and then turning it into an emptiness check instead of directly checking emptiness.
let items: [Int] = []
if items.count == 0 {
print("No items")
}Fix: Use isEmpty when your only goal is to check whether elements exist.
let items: [Int] = []
if items.isEmpty {
print("No items")
}The corrected version works because it directly expresses the real condition you care about.
Mistake 2: Confusing an empty string with nil
A string can be empty, or it can be absent entirely if it is optional. Those are different states.
Problem: This code checks only for nil, so an empty string still passes through as if it contained useful input.
let nickname: String? = ""
if nickname != nil {
print("Nickname is available")
}Fix: Unwrap the optional first, then check whether the string is empty.
let nickname: String? = ""
if let nickname = nickname, !nickname.isEmpty {
print("Nickname is available")
} else {
print("Nickname is missing or empty")
}The corrected version works because it handles both the optional state and the empty-content state.
Mistake 3: Accessing the first element without checking for emptiness
If a collection may be empty, trying to use an index like [0] can crash at runtime.
Problem: This code assumes the array contains at least one element. If it does not, the program can fail with an index out of range error.
let names: [String] = []
print(names[0])Fix: Check isEmpty first, or use safer APIs like first.
let names: [String] = []
if !names.isEmpty {
print(names[0])
} else {
print("No names available")
}The corrected version works because it avoids indexing into an empty array.
Mistake 4: Expecting count to mean the same thing for every collection
count always returns the number of elements, but what counts as an element depends on the collection type.
Problem: This code may lead you to assume a dictionary count reflects the total quantity stored in its values, but it only counts key-value pairs.
let inventory = ["Pens": 10, "Pencils": 20]
print(inventory.count) // 2, not 30Fix: Use count for the number of entries, and calculate totals separately when needed.
let inventory = ["Pens": 10, "Pencils": 20]
let entryCount = inventory.count
let totalUnits = inventory.values.reduce(0, +)
print("Entries: \(entryCount)")
print("Units: \(totalUnits)")The corrected version works because it separates the number of entries from the numeric totals stored as values.
7. Best Practices
Prefer isEmpty for readability
When checking whether a collection has elements, write code that says exactly that.
// Less preferred
if queue.count == 0 {
print("Queue is empty")
}
// Preferred
if queue.isEmpty {
print("Queue is empty")
}The preferred version is easier to understand because it describes the condition directly.
Use count only when the exact number matters
If your UI or logic needs a quantity, count is the right tool.
let unreadMessages = ["Hi", "Reminder", "Update"]
print("Unread messages: \(unreadMessages.count)")This is a good use of count because the number itself is meaningful.
Combine optional unwrapping with emptiness checks carefully
When data may be missing and may also be empty, handle both conditions in a single readable statement.
let searchText: String? = "Swift"
if let searchText = searchText, !searchText.isEmpty {
print("Searching for \(searchText)")
}This pattern is common in forms, search fields, and user input validation.
8. Limitations and Edge Cases
- isEmpty only tells you whether there are zero elements. It does not tell you anything about what those elements are.
- count returns the number of elements, but the meaning of “element” depends on the collection type. For a dictionary, it means key-value pairs. For a string, it means characters.
- An optional collection such as [Int]? does not let you access isEmpty or count until you unwrap it safely.
- A string containing spaces is not empty. For example, " ".isEmpty is false. If you want to treat whitespace-only input as empty, trim it first.
- Some developers search for “Swift count performance.” In standard Swift collections, isEmpty is still the preferred emptiness check because it is semantically correct and may avoid unnecessary work on some collection types.
- If a collection changes over time, do not assume an earlier count value remains correct later in your code. Recheck if the collection may have been mutated.
9. Practical Mini Project
This small example simulates a task manager. It uses isEmpty to decide whether to show a placeholder message and count to display the total number of tasks.
var tasks = ["Buy milk", "Reply to email", "Practice Swift"]
func showTasks(_ tasks: [String]) {
if tasks.isEmpty {
print("No tasks available.")
} else {
print("You have \(tasks.count) task(s):")
for task in tasks {
print("- \(task)")
}
}
}
showTasks(tasks)
tasks.removeAll()
showTasks(tasks)This mini project shows both properties in a realistic context. Before removing all items, count reports the total number of tasks. After removing everything, isEmpty triggers the empty-state message.
10. Key Points
- isEmpty returns true or false depending on whether a collection has elements.
- count returns the number of elements as an Int.
- Use isEmpty for emptiness checks and count when you need the exact size.
- isEmpty is usually clearer than count == 0.
- Different collections count different kinds of elements, such as characters, array items, or dictionary entries.
- Optional collections and optional strings must be unwrapped before you can reliably check emptiness.
11. Practice Exercise
Try building a small program that checks a reading list.
- Create an array of book titles.
- Print a message if the reading list is empty.
- If it is not empty, print the total number of books.
- Then remove all books and print the empty-state message again.
Expected output: First show the number of books, then show a message saying the reading list is empty.
Hint: Use both count and isEmpty in different parts of the program.
var readingList = ["Swift Programming", "Clean Code"]
if readingList.isEmpty {
print("Your reading list is empty.")
} else {
print("Books to read: \(readingList.count)")
}
readingList.removeAll()
if readingList.isEmpty {
print("Your reading list is empty.")
}This solution works because it uses count when the exact total matters and isEmpty when checking whether any books remain.
12. Final Summary
The Swift properties isEmpty and count are simple, but they appear constantly in real code. isEmpty answers the yes-or-no question of whether a collection has any elements, while count gives the exact number of elements. Choosing the right one makes your code clearer and easier to maintain.
As a rule, prefer isEmpty for empty checks and reserve count for cases where the number itself matters. Once you are comfortable with these two properties, a great next step is learning other Swift collection tools such as first, contains, map, and filter.