Ad space (banner)
๐ŸฆSwift Lessons
Lesson 22 / 68

Searching an Array (contains, first)

In this lesson you will learn to search an array in Swift with contains and first, so you can check whether a value is present. This is for anyone searching for "Swift array contains first how to use".

.contains(value) tests whether a value is present, and .first(where:) finds the first element matching a condition.

The sample code confirms presence with fruits.contains("orange") and looks for the first element beginning with "g" using fruits.first(where: { $0.hasPrefix("g") }). Notice how ?? "Not found" supplies a replacement when there is no match.

A common stumbling block for beginners is performance: the more data there is to search, the longer it takes, so faster approaches are worth considering for large volumes. Swift also provides plenty of similar methods, which is part of its readability.

In real-world development this search comes up whenever you need to confirm that a list contains a particular product ID or user name.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)