Swift Array last

The last property returns the last element of the array.

Example

var languages = ["Swift", "C", "Java"]

// check if leanguages is empty or not var result = languages.last
print(result!) // Output: Java

last Syntax

The syntax of the array last property is:

array.last 

Here, array is an object of the Array class.


last Return Values

The last property returns the last element of array.

Note: The last property returns an optional value, so we need to unwrap it. There are different techniques to unwrap optionals. To learn more about optionals, visit Swift Optionals.


Example 1: Swift Array last

var names = ["Gregory", "Perry", "Nadal"]

// return last element of names
print("Last Name of Array: ", names.last!) 

var even = [2, 4, 6, 8, 10]

// check last element of even
print("Last Even Number:", even.last!)

Output

last Name of Array:  Nadal
last Even Number: 10

Here, the last element of the names array is "Nadal", so the last property returns "Nadal" string.

Similarly, the last element of the even array is 10, so the property returns 10.

Note: Here we have used ! to force unwrap the optional. To learn more about forced unwrapping, visit Optional Forced Unwrapping.

Did you find this article helpful?