Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
first
swift
communitycreator

What is array.first in Swift?

Theodore Kelechukwu Onyejiaku

Overview

The first property of an array in Swift returns the first element of the array.

Syntax

arr.first

Parameters

This does not take any parameters.

Return value

The value returned is the first element of the 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 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
Get first elements of arrays with "first" property

Explanation

  • Lines 2–4: We create arrays gnaam, letters, and numbers.
  • Lines 7–9: We use the 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.
  • Line 12–14: We print the results.

RELATED TAGS

array
first
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring