Swift
programming
arrays
count occurrences
Swift tutorial

How to count occurrences of an element in a Swift array?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Counting how many times a value appears in a Swift array is a simple linear scan problem. The most direct solution is to filter the array or reduce it while comparing each element to the target value.

The best method depends on whether you are doing a one-off count or many repeated counts. For one count, a single pass is fine. For many counts, building a frequency table is usually more efficient.

Count With filter

For a readable one-off count, filter is the most common answer.

swift
let numbers = [1, 2, 3, 2, 2, 4]
let count = numbers.filter { $0 == 2 }.count
print(count)

This is concise and idiomatic Swift.

It works for any array element type that supports equality comparison, which usually means the type conforms to Equatable.

Count With reduce

If you want to stay in one explicit pass without creating an intermediate filtered array, use reduce.

swift
1let numbers = [1, 2, 3, 2, 2, 4]
2let count = numbers.reduce(0) { partial, value in
3    partial + (value == 2 ? 1 : 0)
4}
5print(count)

This can be a good fit when you are already reducing for another reason or want complete control over the accumulation logic.

Make It Reusable

You can package the pattern in a helper function.

swift
1func occurrences<T: Equatable>(of target: T, in array: [T]) -> Int {
2    array.reduce(0) { $0 + ($1 == target ? 1 : 0) }
3}
4
5print(occurrences(of: "a", in: ["a", "b", "a", "c"]))

This keeps the calling code clear when the pattern appears often.

When a Frequency Dictionary Is Better

If you need counts for many different values, repeatedly scanning the array is wasteful. Build a frequency dictionary once.

swift
1let words = ["a", "b", "a", "c", "b", "a"]
2var frequencies: [String: Int] = [:]
3
4for word in words {
5    frequencies[word, default: 0] += 1
6}
7
8print(frequencies["a"] ?? 0)
9print(frequencies["b"] ?? 0)

This is especially useful when you have many lookup queries after the initial pass.

What About Custom Types?

For custom objects, the same approach works if the type conforms to Equatable.

swift
1struct User: Equatable {
2    let id: Int
3}
4
5let users = [User(id: 1), User(id: 2), User(id: 1)]
6let count = users.filter { $0 == User(id: 1) }.count
7print(count)

Without Equatable, Swift does not know how to compare instances for equality.

Complexity Matters

A single count through an array is O(n). That is completely normal because you may need to inspect every element.

If you repeat that many times for different targets, the total cost becomes larger. That is when the frequency-dictionary approach pays off, because you do the scan once and look up counts afterward.

Common Pitfalls

A common mistake is optimizing too early. For one target in one array, filter { ... }.count is clear and usually good enough.

Another mistake is building a full frequency dictionary when you only need one count once. That adds complexity without real benefit.

Developers also sometimes forget that custom types must define equality meaningfully before element counting can work cleanly.

Finally, if the element type is floating-point, think carefully about equality rules before relying on exact comparisons.

Summary

  • For a one-off count, array.filter { $0 == target }.count is the clearest solution.
  • 'reduce gives you the same result with explicit accumulation logic.'
  • For many count queries, build a frequency dictionary once.
  • Custom element types usually need Equatable conformance.
  • The right choice depends more on query pattern than on syntax preference.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.