find the first element in an array in swift

To find the first element in an array in Swift, you can use the first property of the Array class. Here's an example:

main.swift
let arr = [1, 2, 3, 4, 5]
if let firstElement = arr.first {
    print(firstElement) // Output: 1
}
99 chars
5 lines

In this example, we created an array of integers and used the first property to get the first element of the array. The first() method returns an optional value because the array might be empty. To safely unwrap the optional value, we used an if let statement to bind the first element of the array to a non-optional constant named firstElement.

If the array is empty, first will return nil, so the if let code block won't be executed.

gistlibby LogSnag