OneBite.Dev - Coding blog in a bite size

Search For A Specific Element In An Array In Swift

Code snippet for how to Search For A Specific Element In An Array In Swift with sample and detail explanation

Whether you’re a beginner or an experienced Swift developer, knowing how to search for a specific element in an array is a valuable skill. This article provides a straightforward guide to performing this task in Swift with a simple, easy-to-understand code snippet.

Code snippet: Search For A Specific Element In An Array In Swift

Here is a quick sample code showing how to search for a specific element in an array using Swift.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
if let index = numbers.firstIndex(of: 5) {
    print("The number 5 found at index \(index) in the array.")
} else {
    print("The number 5 is not found in the array.")
}

Code Explanation: Search For A Specific Element In An Array In Swift

Now let’s break down the code and understand each step.

Firstly, we have a numbers array let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]. It’s just a simple array of integers.

Secondly, we use Swift’s firstIndex(of:) method to search for a specific item in an array. This method returns the first index where the specified value appears in the array: if let index = numbers.firstIndex(of: 5).

If the number is found in the array, we will print the index of the number. Here, \(index) will be replaced by the index of the number 5 in the array: print("The number 5 found at index \(index) in the array.").

In case the requested number is not found inside the array, the firstIndex(of:) method will return nil, then the else block will be executed: else { print("The number 5 is not found in the array.") }.

This simple piece of Swift code is capable of searching any specific element in an array and informs you about its presence, making it a valuable tool in your Swift programming arsenal. This method works for arrays of all data types, not just integers.

swift