OneBite.Dev - Coding blog in a bite size

Count The Number Of Occurrences Of A Specific Element In An Array In Swift

Code snippet for how to Count The Number Of Occurrences Of A Specific Element In An Array In Swift with sample and detail explanation

Working with arrays in Swift has never been easier! This article will guide you through simple steps on how to count the number of occurrences of a particular element in an array.

Code snippet: Counting occurrences of an element in an Array

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

Code Explanation: Counting occurrences of an element in an Array

This code snippet is straightforward and easy to understand. Let’s break it down step-by-step:

  1. First, we declare and initialize an array with let array = [1, 2, 3, 4, 2, 1, 3, 4, 3, 2, 1, 4, 1]. This array is predefined for this example, but in a real-world application, it could come from any source of data.

  2. Next, we define the element we want to count - let elementToCount = 1. In this example, we want to count the number of occurrences of the number 1.

  3. Then, we apply the filter method on the array with array.filter { $0 == elementToCount }. The filter function forms a new array containing only those items that satisfy the condition specified in the closure. In our case, the condition $0 == elementToCount checks if the current element $0 is equal to elementToCount.

  4. Once the new filtered array has been created with only the elements that meet our condition, we then use the count property, which returns the number of elements in an array. In this way, array.filter { $0 == elementToCount }.count returns the number of occurrences of elementToCount in the array.

  5. Finally, we print out the result with print(count), which in this example will print out the number 4, since the number 1 is present four times in our array.

That’s it! With this simple Swift code, you can easily count the occurrences of a specific element in an array. Happy Coding!

swift