What is array.last in Swift?

Overview

We can use the last array instance property to get the last element of an array in Swift.

Syntax

arr.last

Return value

The value returned is the last element of an array.

Example

// create arrays
var gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook", "Meta"];
var letters = ["a", "b", "c", "d", "e"];
var numbers = [1, 2, 3];
// get last elements
let last1 = gnaam.last ?? "";
var last2 = letters.last ?? "";
var last3 = numbers.last ?? 0;
// print results
print(last1); // Meta
print(last2); // e
print(last3); // 3

Explanation

  • Lines 2–4: We create arrays gnaam, letters, and numbers.
  • Lines 7–9: We use the last array instance property to get the last element of each array. We store the results in variables last1, last2, and last3. The question marks in the code returns "" for the first and second array and returns 0 for the third array if they are empty or nil.
  • Line 12–14: We print the results.

Free Resources