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-
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-
So we have found the last 4 elements from the array and stored them in
Our next step would be to print these elements-
The output would be:
[3, 9, 1, 2]
Leave a Reply