Swift .first()
The .first() method returns the first element of the array that fulfills the specified condition. Otherwise, it returns nil.
Note:
.first()is a method while.firstis a property. Details about the.firstarray property can be found near the bottom of this entry.
Syntax
arrayName.first(where: { condition })
The .first() method takes a single condition parameter. It is a closure that returns a boolean value indicating whether a given array element is a match.
Example
var values = [3, 4, 5, 6, 7]let greaterThanFive = values.first(where: { $0 > 5 })print(greaterThanFive!) // Force unwrapping optional
In the example above, the .first() method is searching through the values array. The first item that meets the condition of being greater than 5 will be returned.
This will output:
6
The .first Property
The .first property returns the first element of the array.
Syntax
arrayName.first
Note: The
.firstproperty returns an optional value that should be unwrapped. There are different techniques to unwrap optionals.
Example
var numbers = [5, 1, 8, 4]print(numbers.first!)
In the example above, the .first property of the numbers array is printed out. The .first property will return the first item of the numbers array as an optional value. ! forces the expression to unwrap the value of the returned first element.
Note: Force unwrapping optionals in this way is not recommended because it does not handle
nilcases.
After unwrapping the value of the returned first element, the output will be:
5
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Swift on Codecademy
- Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
- Includes 7 Courses
- With Certificate
- Beginner Friendly.13 hours
- A powerful programming language developed by Apple for iOS, macOS, and more.
- Beginner Friendly.12 hours