optional array
array empty check
programming
array handling
coding tutorial

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:

swift
1let items: [String]? = nil
2
3if items?.isEmpty ?? true {
4    print("No items")
5}

Here is what it does:

  • 'items?.isEmpty produces an optional Bool'
  • if items is nil, the expression becomes nil
  • '?? true turns that nil into true'

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.

swift
1let items: [String]? = []
2
3if let items = items {
4    if items.isEmpty {
5        print("Loaded, but empty")
6    } else {
7        print("Loaded with \(items.count) items")
8    }
9} else {
10    print("Not loaded yet")
11}

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.

swift
1func isNilOrEmpty<T>(_ array: [T]?) -> Bool {
2    array?.isEmpty ?? true
3}
4
5print(isNilOrEmpty(nil))        // true
6print(isNilOrEmpty([Int]()))    // true
7print(isNilOrEmpty([1, 2, 3]))  // false

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:

swift
if items?.isEmpty ?? true {
    print("Nothing to show")
}

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:

swift
items?.isEmpty

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:

swift
1let names: Set<String>? = nil
2let lookup: [String: Int]? = [:]
3
4print(names?.isEmpty ?? true)
5print(lookup?.isEmpty ?? true)

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:

  • 'nil means 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 nil and empty as the same state without deciding whether that is actually correct.
  • Force-unwrapping the array just to check isEmpty.
  • Using count == 0 when isEmpty expresses the intent more clearly.
  • Forgetting that items?.isEmpty returns an optional Bool, not a plain Bool.
  • Writing overly complex unwrapping code for a condition that optional chaining already handles neatly.

Summary

  • Use array?.isEmpty ?? true when nil and empty should both count as "no items."
  • Use if let when nil and empty need different meanings.
  • Prefer isEmpty over count == 0 for readability.
  • Optional chaining plus nil-coalescing is the idiomatic Swift solution.
  • Decide the data semantics first, then choose the syntax that matches them.

Course illustration
Course illustration

All Rights Reserved.