Swift – Get First Element of Array

To get the first element of an array in Swift, access first property of this Array.

Array.first returns the first element of this array. If the array is empty, then this property returns nil.

Syntax

The syntax to call access first element of Array array is

array.first

We may use this property with if statement as shown in the following.

if let firstElement = array.first {
    //code
}
ADVERTISEMENT

Examples

In the following program, we take an array of size five, and get the first element of this array.

main.swift

var nums = [ 2, 4, 6, 8, 10 ]
if let firstElement = nums.first {
    print("First Element : \(firstElement)")
}

Output

First Element : 2
Program ended with exit code: 0

In the following program, we will take an empty array, and try to get the first element of this array. Also, we add else block to handle if the array is empty.

main.swift

var nums: [Int] = []
if let firstElement = nums.first {
    print("First Element : \(firstElement)")
} else {
    print("Array is empty. No first element.")
}

Output

Array is empty. No first element.
Program ended with exit code: 0

Conclusion

In this Swift Tutorial, we learned how to get the first element of an Array in Swift programming.