Get the last n elements of an array in Swift

This tutorial is all about finding the last elements of an array in Swift. This simply means working on the array to fetch the last few elements which is sometimes a crucial task while working with the arrays. So here we came up with this article to accomplish this task.

As a developer, you sometimes need to find a few elements, may to even fetch from the last, for example, the last 4 elements in a given array.


The array is-


We need to pick the last 4 elements.

The output should result-


This is our given task for today.

Starting with creating an array of integer elements-

var array1=[2,4,1,3,5,7,3,9,1,2]

We have successfully created an array of integer elements.

We now need to find the last elements and store them. This can be easily done using the suffix(). You need to pass the number of elements you want to print on your screen in the parameter in the suffix.

suffix() in Swift

The syntax for this will be-

let lastfour=array1.suffix(4)

So we have found the last 4 elements from the array and stored them in lastfour.

Our next step would be to print these elements-


The output would be:

[3, 9, 1, 2]

Leave a Reply

Your email address will not be published. Required fields are marked *