To get the last element in an array in Swift, you can use array indexing similar to other languages.
In this example,
numbers
with some elements.numbers[numbers.count - 1]
and store it in the variable lastNumber
.lastNumber
.let numbers = [1, 2, 3, 4, 5]
let lastNumber = numbers[numbers.count - 1]
print("Last number is:", lastNumber)
Last number is: 5
In this example,
fruits
with some elements.fruits[fruits.count - 1]
and store it in the variable lastFruit
.lastFruit
.let fruits = ["apple", "banana", "cherry"]
let lastFruit = fruits[fruits.count - 1]
print("Last fruit is:", lastFruit)
Last fruit is: cherry
In this tutorial, we learned How to get Last Element in Array in Swift language with well detailed examples.