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.swift99 chars5 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