Get the last N elements from an array in Swift


In this Swift programming tutorial, you will learn how to get the last N elements from an array with the help of an easy example.

In Swift, there is a method suffix() that can help us to perform the task. We have to provide an integer as the argument to the suffix() method. In return, the method returns the array with the specific number of elements from the ending of the array. In this way, we can get the last N elements from an array in Swift.

Suppose we have an array:

let fruitsArray = ["Apple", "Mango", "Pineapple", "Banana", "Pear"]

From the above array, we have to get the last 2 items. We can do it using the suffix() method like you can see in the example below:

let fruitsArray = ["Apple", "Mango", "Pineapple", "Banana", "Pear"]

let lastTwofruits = fruitsArray.suffix(2)

print(lastTwofruits)

Output:

["Banana", "Pear"]

As you can see in the output, we have successfully been able to get the last 2 elements from our array.

In our code, we have applied the suffix() method to the array fruitsArray. We pass 2 as the argument as we want to get the last two items from the array:

fruitsArray.suffix(2)

If we have to get the last three array elements, then we had to pass 3 as the argument:

fruitsArray.suffix(3)