We can use the last
array instance property to get the last element of an array in Swift.
arr.last
The value returned is the last element of an array.
// 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
gnaam
, letters
, and numbers
.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.