Swift isEmpty vs count: Check If an Array or String Is Empty
To check whether a Swift array, string, set or dictionary is empty, use isEmpty: if items.isEmpty { … }. To find out how many elements it has, use count. Prefer isEmpty to count == 0: for an array both are instant, but for a String or a lazy collection, count walks every element just to answer a yes-or-no question. This page also covers first and last, counting with a condition using count(where:), why one string has four different counts, and the edge cases that break the simple check.
Difficulty: Beginner
Helpful to know first: how Swift arrays, strings and dictionaries are created, what an optional is, and how an if statement works.
Checking for Empty and Counting Elements
Every Swift collection has the same two properties, so the code looks identical for arrays, sets, dictionaries and strings.
let tasks = ["Write report", "Email Sam", "Book flights"]
let tags: Set<String> = []
let settings: [String: Bool] = ["darkMode": true]
let note = ""
print(tasks.isEmpty, tasks.count) // Output: false 3
print(tags.isEmpty, tags.count) // Output: true 0
print(settings.isEmpty, settings.count) // Output: false 1
print(note.isEmpty, note.count) // Output: true 0
if tasks.isEmpty {
print("Nothing to do")
} else {
print("\(tasks.count) tasks left") // Output: 3 tasks left
}false 3 true 0 false 1 true 0 3 tasks left
- isEmpty is a Bool: true when there are no elements.
- count is an Int: the number of elements.
- For a dictionary, an element is one key-value pair, so settings.count is 1, whatever the values are.
- An empty string "" is a collection of zero characters, so it has isEmpty and count like any array.
The if/else shows the usual pattern: ask isEmpty to choose the branch, and use count only where you need the number.
Other Ways to Ask "Is It Empty?" and "How Many?"
isEmpty versus count == 0
Both give the same answer. The difference is what they cost. isEmpty only has to find out whether a first element exists. count is instant for types that store their size, and a walk over every element for the others.
| Type | isEmpty | count |
|---|---|---|
| Array, ranges, Set, Dictionary | instant | instant (the size is stored) |
| String, Substring | instant | walks every character |
| A lazy filter | stops at the first match | tests every element |
A closure that counts its own calls makes the difference visible:
var checks = 0
let evens = (1...1_000_000).lazy.filter { number in
checks += 1
return number.isMultiple(of: 2)
}
print(evens.isEmpty) // Output: false
print(checks) // Output: 2
checks = 0
print(evens.count == 0) // Output: false
print(checks) // Output: 1000000false 2 false 1000000
isEmpty tested 1, found 2, and stopped. count == 0 ran the closure a million times for the same answer. The same applies to strings: text.count has to group the text into characters from start to end, so a count == 0 check inside a loop over long strings does real work every time. How lazy pipelines run is explained in Swift lazy collections.
first and last instead of an index
Often you do not want to know that a collection has elements; you want the element. first and last return an optional that is nil for an empty collection, so one expression answers both questions.
let scores = [72, 95, 88]
let noScores: [Int] = []
if let opening = scores.first {
print("First score: \(opening)") // Output: First score: 72
}
print(noScores.first ?? 0) // Output: 0
print(noScores.last as Any) // Output: nilFirst score: 72 0 nil
This is safer than checking isEmpty and then reading scores[0], because there is no second step that can drift out of sync with the check. The full guide is Swift first and last.
Counting only the elements that match: count(where:)
To count elements that pass a test, Swift 6.0 and later have count(where:) on every sequence. On older compilers, filter(_:) followed by count gives the same number but builds a temporary array first.
let words = ["apple", "kiwi", "banana", "fig"]
print(words.count(where: { $0.count > 3 })) // Output: 3
print(words.filter { $0.count > 3 }.count) // Output: 3
print(words.contains { $0.count > 5 }) // Output: true3 3 true
count(where:) is compiled into your app, so it needs a Swift 6 compiler (Xcode 16 or later) but not a newer operating system. If you only need to know whether any element matches, use contains(where:), which stops at the first match; see Swift contains and allSatisfy.
| Question | Use |
|---|---|
| Is it empty? | isEmpty |
| How many elements? | count |
| Give me the first or last one, if any | first, last |
| How many match a condition? | count(where:) |
| Does any element match? | contains(where:) |
| Do all elements match? | allSatisfy(_:) |
Which Count Do You Need for a String?
String.count counts characters as a reader sees them (extended grapheme clusters). The same text also has a count of Unicode scalars, of UTF-16 code units and of UTF-8 bytes, and the four numbers often differ.
let accented = "cafe\u{301}" // "café" written with a combining accent
let thumbs = "👍🏽"
let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}" // 👨👩👧
print(accented.count, accented.unicodeScalars.count, accented.utf16.count, accented.utf8.count)
// Output: 4 5 5 6
print(thumbs.count, thumbs.unicodeScalars.count, thumbs.utf16.count, thumbs.utf8.count)
// Output: 1 2 4 8
print(family.count, family.unicodeScalars.count, family.utf16.count, family.utf8.count)
// Output: 1 5 8 184 5 5 6 1 2 4 8 1 5 8 18
The family emoji is one character built from three people joined by two invisible zero-width joiners: five scalars in all. Also note that "a\r\nb".count is 3, because a carriage return plus line feed counts as one character, while its utf8.count is 4.
| Property | Counts | Use it for |
|---|---|---|
| count | Characters a person sees | User-facing limits such as "at most 20 characters" |
| unicodeScalars.count | Unicode code points | Unicode processing and some text formats |
| utf16.count | UTF-16 code units | NSString length, NSRange, JavaScript's length |
| utf8.count | Bytes in UTF-8 | Byte limits: database columns, network payloads, file sizes |
Two strings can be equal and still have different byte counts: "café" typed with a single é is 5 UTF-8 bytes, the combining version above is 6, and Swift's == says they are the same. For a native Swift string, utf8.count is usually fast because Swift stores strings as UTF-8; count is the one that always walks the text. More on characters in Swift Unicode and grapheme clusters and on the cost of string operations in Swift string performance.
Edge Cases: Optionals, Blank Strings, and Plain Sequences
An optional collection is not empty, it is missing
An optional array has no isEmpty of its own. Writing results.isEmpty on a [String]? fails with value of optional type '[String]?' must be unwrapped to refer to member 'isEmpty' of wrapped base type '[String]'. Use optional chaining and decide what nil should mean:
let results: [String]? = nil
if results?.isEmpty ?? true {
print("No results") // Output: No results
}
print(results?.count ?? 0) // Output: 0No results 0
?? true treats "no array" the same as "empty array". When the two cases need different handling, unwrap first with guard let results, !results.isEmpty else { … }; see Swift optional binding.
A string of spaces is not empty
isEmpty is only true for "". To treat blank input as empty without importing Foundation, check that every character is whitespace:
let input = " "
print(input.isEmpty) // Output: false
print(input.allSatisfy(\.isWhitespace)) // Output: true
print("".allSatisfy(\.isWhitespace)) // Output: truefalse true true
allSatisfy returns true for an empty collection, so this one check covers both "empty" and "only spaces or newlines".
A plain Sequence has no count or isEmpty
isEmpty and count belong to Collection. Some types, such as the result of stride(from:to:by:), are only a Sequence. Asking for steps.isEmpty gives value of type 'StrideTo<Int>' has no member 'isEmpty'. Asking for steps.count gives a more confusing error, generic parameter 'E' could not be inferred, because the only count a sequence has is the method count(where:).
let steps = stride(from: 0, to: 10, by: 2)
print(steps.count(where: { _ in true })) // Output: 5
print(steps.reduce(0) { total, _ in total + 1 }) // Output: 55 5
Both lines go through the whole sequence once. underestimatedCount is not a replacement: it is only a lower bound. The difference between the two protocols is explained in Swift Sequence and Collection protocols.
Common Mistakes When Checking for Empty Collections
Reading items[0] without a check
Subscripting an empty array does not return nil; it stops the program.
Problem: When the list is empty, tasks[0] stops the program; a debug build reports Fatal error: Index out of range.
func firstTask(_ tasks: [String]) -> String {
tasks[0]
}
print(firstTask([]))Fix: Use first, which is nil for an empty array, and supply a fallback.
func firstTask(_ tasks: [String]) -> String {
tasks.first ?? "No tasks"
}
print(firstTask([])) // Output: No tasksNo tasks
The corrected version works because first combines the emptiness check and the read in one safe step.
Checking for nil but not for empty
An optional string can be nil, empty, or filled. A check for nil alone lets the empty case through.
Problem: The nickname is "", not nil, so the greeting prints Hello, with nothing after it.
let nickname: String? = ""
if nickname != nil {
print("Hello, \(nickname!)")
}Hello,
Fix: Unwrap and test for emptiness in the same condition.
let nickname: String? = ""
if let nickname, !nickname.isEmpty {
print("Hello, \(nickname)")
} else {
print("Hello, guest") // Output: Hello, guest
}Hello, guest
The corrected version works because the if continues only when the value exists and has at least one character.
Using count for a limit that is really in bytes
Database columns, push notification payloads and many APIs limit text by bytes, not by characters.
Problem: Two family emoji are 2 characters but 36 bytes, so a 16-byte limit checked with count lets the name through and the server rejects or cuts it.
let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}"
let username = family + family
let maxBytes = 16
print(username.count <= maxBytes) // Output: truetrue
Fix: Measure the same unit that the limit uses.
let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}"
let username = family + family
let maxBytes = 16
print(username.utf8.count, username.utf8.count <= maxBytes) // Output: 36 false36 false
The corrected version works because utf8.count is the number of bytes that will actually be stored or sent.
Using filter(_:).count to ask whether anything matches
Counting all matches just to compare the number with zero does more work than the question needs.
Problem: filter tests every order and builds a new array of the overdue ones, even though the first overdue order already answers the question.
let daysLate = [0, 3, 0, 12, 0]
if daysLate.filter({ $0 > 0 }).count > 0 {
print("Some orders are late") // Output: Some orders are late
}Some orders are late
Fix: Use contains(where:), which stops at the first match and allocates nothing.
let daysLate = [0, 3, 0, 12, 0]
if daysLate.contains(where: { $0 > 0 }) {
print("Some orders are late") // Output: Some orders are late
}Some orders are late
The corrected version works because it states the real question, "is there any?", and stops as soon as it has the answer.
Predict the Output
What does this print?
let flag = "🇯🇵"
let accent = "e\u{301}"
print(flag.count, flag.unicodeScalars.count, flag.utf8.count)
print(accent.isEmpty, accent.count, accent.utf16.count)Show answer
It prints 1 2 8 and then false 1 2.
A flag emoji is one character made of two "regional indicator" scalars (J and P), and each of them takes 4 bytes in UTF-8. "e\u{301}" is the letter e followed by a combining acute accent: one visible character, two scalars, and two UTF-16 code units. It is not empty, even though it looks like a single letter.
Summary
- Use isEmpty to check for no elements and count when you need the number.
- count is instant for arrays, ranges, sets and dictionaries, but walks every element of a String or a lazy filter; isEmpty never has to.
- first and last return nil for an empty collection; prefer them to items[0].
- Count matches with count(where:) (Swift 6.0+) or filter(_:).count; ask "any?" with contains(where:).
- A string has four counts: characters, Unicode scalars, UTF-16 units and UTF-8 bytes. Pick the one your limit is measured in.
- Optional collections need ?.isEmpty ?? true or unwrapping, and plain sequences have no count or isEmpty at all.
Next, read Swift first and last to work with the boundary elements safely once you know a collection has some.