Swift Array first

The first property returns the first element of the array.

Example

var languages = ["Swift", "C", "Java"]

// check if leanguages is empty or not var result = languages.first
print(result!) // Output: Swift

first Syntax

The syntax of the array first property is:

array.first 

Here, array is an object of the Array class.


first Return Values

The first property returns the first element of array.

Note: The first property returns an optional value, so we need to unwrap it. There are different techniques to unwrap optionals. To learn more about optionals, visit Swift Optionals.


Example: Swift Array first

var names = ["Gregory", "Perry", "Nadal"]

// return first element of names print("First Name of Array: ", names.first!)
var even = [2, 4, 6, 8, 10]
// check first element of even print("First Even Number:", even.first!)

Output

First Name of Array:  Gregory
First Even Number: 2

Here, the first element of the names array is "Gregory", so the first property returns "Gregory" string.

Similarly, the first element of the even array is 2, so the property returns 2.

Note: Here we have used ! to force unwrap the optional. To learn more about forced unwrapping, visit Optional Forced Unwrapping.

Did you find this article helpful?