The first
property of an array in Swift returns the first element of the array.
arr.first
This does not take any parameters.
The value returned is the first element of the array.
// create arrays var gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook", "Meta"]; var letters = ["a", "b", "c", "d", "e"]; var numbers = [1, 2, 3]; // get first elements let first1 = gnaam.first ?? ""; var first2 = letters.first ?? ""; var first3 = numbers.first ?? 0; // print results print(first1); // Google print(first2); // a print(first3); // 1
gnaam
, letters
, and numbers
.first
array instance property to get the first element of each array. We store the results in variables first1
, first2
, and first3
. 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
.RELATED TAGS
CONTRIBUTOR
View all Courses