OneBite.Dev - Coding blog in a bite size

Get The Last Element Of Array In Swift

Code snippet for how to Get The Last Element Of Array In Swift with sample and detail explanation

Working with arrays is a common task in any programming language and Swift is no exception. In this article, we will discover a simple and effective way to get the last element of an array in Swift.

Code Snippet to Get The Last Element Of Array In Swift

Below given is a simple Swift code snippet that fetches the last element from the array:

let fruitsArray = ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig"]
if let lastFruit = fruitsArray.last {
    print("The last fruit in the array is: \(lastFruit)")
}

If you run this code, it will output: The last fruit in the array is: Fig.

Code Explanation for Getting The Last Element Of Array In Swift

Let’s break down the code:

  1. Declaration of an array: The first line of the code declares an array named fruitsArray containing six strings, each representing a different fruit.
let fruitsArray = ["Apple", "Banish", "Cherry", "Date", "Elderberry", "Fig"]
  1. Using last property: The last property of the Array is used to get the last element in the array. This property is optional which means it will return nil if the Array is empty (contains no elements). Swift’s built-in optional binding (using if let) can be used to check and safely unwrap the last element of the array.
if let lastFruit = fruitsArray.last {
    print("The last fruit in the array is: \(lastFruit)")
}

In this code snippet, fruitsArray.last returns the last element of the array (in this case, “Fig”). This value is then safely unwrapped using optional binding and stored in the constant lastFruit.

If the array had been empty, fruitsArray.last would have returned nil, and the code within the braces { } would have been skipped.

In conclusion, using the last property of an array in Swift provides a simple, readable, and safe way to obtain the last element of an array. It’s important to always check for nil when using optional properties like last to avoid runtime errors in your code.

swift