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 arraysvar gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook", "Meta"];var letters = ["a", "b", "c", "d", "e"];var numbers = [1, 2, 3];// get last elementslet last1 = gnaam.last ?? "";var last2 = letters.last ?? "";var last3 = numbers.last ?? 0;// print resultsprint(last1); // Metaprint(last2); // eprint(last3); // 3
Explanation
- Lines 2–4: We create arrays
gnaam,letters, andnumbers. - Lines 7–9: We use the
lastarray instance property to get the last element of each array. We store the results in variableslast1,last2, andlast3. 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.