Check if optional array is empty
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
With an optional array, you usually need to answer two different questions: "is the value nil?" and "if it exists, is it empty?" In Swift, the cleanest code depends on whether you want to treat nil and an empty array as the same condition or as two different states.
Treat nil and Empty as Equivalent
If your logic is simply "there is nothing to process," then this is the most concise pattern:
Here is what it does:
- '
items?.isEmptyproduces an optionalBool' - if
itemsisnil, the expression becomesnil - '
?? trueturns thatnilintotrue'
So this condition is true for both nil and [].
Distinguish nil from an Empty Array
Sometimes nil means "not loaded yet" while an empty array means "loaded, but there were no results." In that case, keep the states separate.
This version is longer, but it preserves the semantics of the data instead of collapsing them together.
A Useful Helper
If you check optional arrays often, wrap the rule in a helper so the meaning is obvious at the call site.
This is particularly useful in view models, networking code, and UI state checks where the same condition appears repeatedly.
Do Not Use count == 0 Unless You Need It
In Swift, isEmpty is preferred over count == 0 for readability and intent:
That reads more clearly than comparing counts, and it signals that you care about emptiness rather than size.
Optional Chaining Is the Key Idea
The core Swift feature here is optional chaining. Instead of unwrapping first and then reaching the property, you can write:
That safely accesses isEmpty only when the array exists. Combined with the nil-coalescing operator, it becomes an expressive one-line check.
You can use the same pattern with other collection types as well:
Pick the Semantics Before the Syntax
The real design decision is not the operator choice. It is whether nil should mean the same thing as empty. In many apps:
- '
nilmeans unavailable, uninitialized, or not yet fetched' - empty means initialized successfully with no data
That difference can matter for loading states, retry logic, and user messaging.
Common Pitfalls
- Treating
niland empty as the same state without deciding whether that is actually correct. - Force-unwrapping the array just to check
isEmpty. - Using
count == 0whenisEmptyexpresses the intent more clearly. - Forgetting that
items?.isEmptyreturns an optionalBool, not a plainBool. - Writing overly complex unwrapping code for a condition that optional chaining already handles neatly.
Summary
- Use
array?.isEmpty ?? truewhenniland empty should both count as "no items." - Use
if letwhenniland empty need different meanings. - Prefer
isEmptyovercount == 0for readability. - Optional chaining plus nil-coalescing is the idiomatic Swift solution.
- Decide the data semantics first, then choose the syntax that matches them.

