by Sai gowtham

How to get the last element from an array in Swift

Learn, how to get the last element of a given array in Swift.

Consider, we have the following array:

var cars = ["Skoda", "Volvo", "BMW"];

To access the last element (BMW) from an above array, we can use the subscript syntax [ ] by passing its index.

In Swift arrays are zero-indexed. The first element index is 0, to get the last element index we need to subtract the array.count property with 1.

Example:

var cars = ["Skoda", "Volvo", "BMW"];

let lastElement = cars[cars.count-1]

print(lastElement) // "BMW"

Similarly, we can also use the last instance property like this.

var cars = ["Skoda", "Volvo", "BMW"];

if let lastElement = cars.last {
    print(lastElement) // "BMW"
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course