Swift – Get Last Element of Array

To get the last element of an array in Swift, access last property of this Array.

Array.last returns the last element of this array. If the array is empty, then this property returns nil.

Syntax

The syntax to call access last element of Array array is

</>
Copy
array.last

We may use this property with if statement as shown in the following.

</>
Copy
if let lastElement = array.last {
    //lastElement contains the last element
}

Examples

In the following program, we take an array of size five, and get the last element of this array.

main.swift

</>
Copy
var nums = [ 2, 4, 6, 8, 10 ]
if let lastElement = nums.last {
    print("Last Element : \(lastElement)")
}

Output

Last Element : 10
Program ended with exit code: 0

In the following program, we will take an empty array, and try to get the last element of this array. Also, we add else block to handle if the array is empty.

main.swift

</>
Copy
var nums: [Int] = []
if let lastElement = nums.last {
    print("Last Element : \(lastElement)")
} else {
    print("Array is empty. No last element.")
}

Output

Array is empty. No last element.
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to get the last element of an Array in Swift programming.