OneBite.Dev - Coding blog in a bite size

Get The Nth Element Of Array In Swift

Code snippet for how to Get The Nth Element Of Array In Swift with sample and detail explanation

Working with arrays in Swift is a fundamental part of programming. This short article will guide you on how to retrieve the Nth element of an array in Swift.

Code Snippet: Get The Nth Element of an Array

Suppose you have an array named myArray. The Swift code to get the Nth element is:

if n<myArray.count{
    let element = myArray[n]
    print(element)
} else {
    print("The array contains less than \(n) elements.")
}

Code Explanation: Get The Nth Element of an Array

In Swift, array indexing starts at 0. So if you have an array of 5 elements (e.g. myArray = ["a", "b", "c", "d", "e"]), element “a” is at the 0th position, “b” is at 1st position, and so on.

The above code starts with an if statement, which checks whether the array has as many elements as the number n. If the number n you input is less than the total number of elements in the array (myArray.count), you won’t get an “index out of range” error. This is why we use this condition: to avoid such errors.

The line let element = myArray[n] is used to get the Nth element from the array. Here, n is the index of the element that you want to retrieve. It should be noted that n is zero-based, i.e., counting starts from 0.

Thus, if you want to get the 3rd element from the array, you should use 2 as the value of n because the count starts from 0.

Finally, print(element) is used to print the output, i.e., the Nth element of the array.

In case the number n is more than the number of elements present in the array, the output would be “The array contains less than (n) elements”. This is to let you know that the array does not have that many elements.

The above code allows you to safely and efficiently retrieve any element from a Swift array, based on its position or index.

swift