Call contains(_:): fruits.contains("banana") returns true or false. It needs elements that are Equatable; for structs and conditions, pass a closure instead: products.contains { $0.price > 100 }. To get the matching element back, use first(where:), and for its position, firstIndex(of:). Both return an optional that is nil when nothing matches.
Swift arrays have no indexOf that returns -1 and no in operator. The question "is it there?" is answered by contains, which comes in two forms: one that compares with == and one that takes a condition. "Where is it?" and "give me the object" are separate calls that return optionals. The sections below cover both forms of contains, the Equatable conformance your own types need, finding the element or its index, checking several values at once, and when to turn the array into a Set, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1contains(_:): is this value in the array?Recommended
contains(_:) walks the array from the start, compares each element with ==, and returns true at the first match. It works on any array whose elements are Equatable: strings, numbers, characters, enums without associated values, optionals of those, and your own types once they conform. For "not in the array", negate the call with !. The same method exists on every Swift sequence, so a range or a set answers the same question, often without scanning.
let fruits = ["apple", "banana", "cherry"] print(fruits.contains("banana")) print(fruits.contains("Banana")) // Not in the array: negate the call if !fruits.contains("kiwi") { print("no kiwi") } let primes = [2, 3, 5, 7, 11, 13] print(primes.contains(7), primes.contains(8)) // Enums without associated values are Equatable for free enum Weekday { case mon, tue, wed, thu, fri, sat, sun } let weekend: [Weekday] = [.sat, .sun] print(weekend.contains(.sun)) // A range checks its bounds instead of scanning print((1...100).contains(42)) // Optional elements: contains(nil) works too let answers: [Int?] = [3, nil, 9] print(answers.contains(nil), answers.contains(9))
Output
"banana" is found and "Banana" is not: the comparison is exact and case-sensitive, so the second line is false. The negated check prints no kiwi, and the primes give true false for 7 and 8. The Weekday enum never declares Equatable, yet contains(.sun) compiles, because Swift adds it to enums without associated values. (1...100).contains(42) compares 42 with the two bounds rather than visiting a hundred numbers. In an array of Int?, contains(nil) asks whether any slot is empty.
2contains(where:): a condition, or ignoring case
contains(where:) takes a closure that returns a Bool and stops at the first element for which it is true. It works on any element type, Equatable or not, so it is the way to ask about structs ("is any product over $100?") and to compare in a way other than ==. A case-insensitive search is one of those: compare lowercased copies, or call Foundation's caseInsensitiveCompare, which needs import Foundation. With a trailing closure you can drop the where: label, as most code does.
import Foundation struct Product { let name: String let price: Double let inStock: Bool } let products = [ Product(name: "Keyboard", price: 49.0, inStock: true), Product(name: "Mouse", price: 19.5, inStock: false), Product(name: "Monitor", price: 189.0, inStock: true), ] // Any element matching a condition print(products.contains { $0.price > 100 }) print(products.contains { $0.name == "Webcam" }) print(products.contains { !$0.inStock }) // Case-insensitive: compare lowercased copies... let tags = ["Swift", "iOS", "Linux"] let search = "SWIFT" print(tags.contains(search)) print(tags.contains { $0.lowercased() == search.lowercased() }) // ...or let Foundation compare without making copies print(tags.contains { $0.caseInsensitiveCompare("ios") == .orderedSame }) // Substring match inside the elements print(tags.contains { $0.localizedCaseInsensitiveContains("lin") }) print("Straße".caseInsensitiveCompare("STRASSE") == .orderedSame) print("Straße".lowercased() == "STRASSE".lowercased())
Output
The monitor is over 100, there is no webcam, and the mouse is out of stock: true, false, true. A plain tags.contains("SWIFT") is false, while both case-insensitive versions find it. localizedCaseInsensitiveContains checks inside each element, so "lin" matches Linux; for more on that, see checking if a string contains a substring. The last two lines show why Foundation's compare is the safer choice for words: on Linux here it treats Straße and STRASSE as equal (true), while comparing lowercased copies gives false.
3Your own types: add Equatable
Pass a plain struct to contains and the compiler picks the only overload left, the closure one, and complains about that instead. On this page the error is error: missing argument label 'where:' in call, followed by cannot convert value of type 'Point' to expected argument type '(Point) throws -> Bool'. The fix is one word: declare the struct Equatable. When every stored property is Equatable, Swift writes == for you, comparing all of them. Write your own == only when equality means something narrower, such as "same id". Classes get no generated ==; to ask whether this exact instance is in the array, compare identity with ===.
// Declaring Equatable is enough: Swift writes == for you struct Point: Equatable { let x: Int let y: Int } let path = [Point(x: 0, y: 0), Point(x: 1, y: 2), Point(x: 3, y: 4)] print(path.contains(Point(x: 1, y: 2))) print(path.contains(Point(x: 2, y: 1))) // Classes get no synthesized ==; compare identity with === final class Window { let title: String init(title: String) { self.title = title } } let editor = Window(title: "Editor") let open = [editor, Window(title: "Terminal")] let lookalike = Window(title: "Editor") print(open.contains { $0 === editor }) print(open.contains { $0 === lookalike }) print(open.contains { $0.title == lookalike.title }) // Your own ==: two users are equal when their ids match struct User: Equatable { let id: Int var name: String static func == (lhs: User, rhs: User) -> Bool { lhs.id == rhs.id } } let users = [User(id: 1, name: "Ada"), User(id: 2, name: "Linus")] print(users.contains(User(id: 2, name: "L. Torvalds")))
Output
The generated == compares x and y, so (1, 2) is found and (2, 1) is not. For the windows, === finds editor but not lookalike, a separate object with the same title, while comparing titles finds it: decide which question you are asking. The custom == on User ignores the name, so a user with id 2 and a different name still counts as present (true). Keep such an == consistent with how the type is used elsewhere, because firstIndex(of:) and every other == call will use it too.
4Get the element or its index: first(where:) and firstIndex
When you need the matching object, not just a yes or no, use first(where:). It returns the first element for which the closure is true, as an optional, so if let both tests and unwraps it. last(where:) searches from the end. For the position, use firstIndex(of:) with an Equatable value or firstIndex(where:) with a condition, and lastIndex(of:) for the last match. These return Int?, never -1. Older answers call the same thing index(of:) or indexOf; those names were replaced by firstIndex(of:) in Swift 4.2.
struct Book { let title: String let year: Int } let books = [ Book(title: "Dune", year: 1965), Book(title: "Neuromancer", year: 1984), Book(title: "Hyperion", year: 1989), ] // first(where:) returns the element itself, or nil if let book = books.first(where: { $0.year > 1980 }) { print("first after 1980:", book.title) } let old = books.first { $0.year < 1900 } print(old == nil ? "none before 1900" : "found one") // last(where:) searches from the end print(books.last { $0.year > 1980 }?.title ?? "none") // firstIndex(of:) for Equatable elements let colors = ["red", "green", "blue", "green"] if let i = colors.firstIndex(of: "green") { print("green at", i) } print(String(describing: colors.lastIndex(of: "green"))) print(String(describing: colors.firstIndex(of: "pink"))) // firstIndex(where:) for a condition if let i = books.firstIndex(where: { $0.title.hasPrefix("H") }) { print("index \(i): \(books[i].title)") } // Every index that matches let greens = colors.indices.filter { colors[$0] == "green" } print(greens) // A slice keeps the indices of the original array let tail = colors[2...] print(String(describing: tail.firstIndex(of: "green")))
Output
first(where:) stops at Neuromancer even though Hyperion also matches, and last(where:) returns Hyperion. No book is older than 1900, so that search gives nil. "green" appears at 1 and 3: firstIndex(of:) gives green at 1, lastIndex gives Optional(3), and a missing color gives nil. Filtering indices collects every match, [1, 3]. The last line is the gotcha: colors[2...] is a slice that keeps the original numbering, so the green in it is at Optional(3), not 1. Use that index on the slice or on colors, never as an offset from 0.
5Several values at once
To check that all of several values are present, combine allSatisfy with contains, or turn the wanted values into a Set and ask isSubset(of:). For "any of them", nest contains calls, or use isDisjoint(with:) and negate it. filter lists which ones are missing and keeps their order. To count matches, count(where:) reads best, but it was added in Swift 6.0; on older compilers, filter and then count gives the same number.
let pantry = ["flour", "eggs", "milk", "sugar", "butter"] // All of several values let cake = ["flour", "eggs", "sugar"] print(cake.allSatisfy { pantry.contains($0) }) print(Set(cake).isSubset(of: pantry)) // Any of several values let vegan = ["tofu", "oat milk", "sugar"] print(vegan.contains { pantry.contains($0) }) print(!Set(vegan).isDisjoint(with: pantry)) // Which ones are missing, in their original order let pancakes = ["flour", "eggs", "milk", "baking powder", "salt"] print(pancakes.filter { !pantry.contains($0) }) // How many match (count(where:) needs Swift 6.0 or later) print(pantry.count(where: { $0.hasSuffix("r") })) print(pantry.filter { $0.hasSuffix("r") }.count)
Output
Everything for the cake is in the pantry, so both checks print true. Of the vegan list only sugar is there, which is enough for "any". The pancake recipe is missing ["baking powder", "salt"], listed in recipe order; a set difference would give the same items in no particular order. Three pantry items end in r (flour, sugar, butter), counted both ways. isSubset(of:) and isDisjoint(with:) accept the array directly, so only the wanted values need to become a Set.
6Many lookups: build a Set first
contains on an array is a linear search: a miss compares the value with every element. That is fine for one check, but checking a thousand values against a large array multiplies the work. A Set hashes the value and goes straight to where it would be stored, so a lookup costs about the same however big the set is. It needs Hashable elements, which Swift generates for structs and enums the same way as Equatable. The example below counts the work instead of timing it: its OrderID type adds one to a counter on every == and every hash.
// Counts every == and every hash, so you can see the work var comparisons = 0 var hashes = 0 struct OrderID: Hashable { let value: Int static func == (lhs: OrderID, rhs: OrderID) -> Bool { comparisons += 1 return lhs.value == rhs.value } func hash(into hasher: inout Hasher) { hashes += 1 hasher.combine(value) } } // 5,000 shipped orders and 1,000 orders to look up let shipped = (0..<5_000).map { OrderID(value: $0 * 2) } let queries = (0..<1_000).map { OrderID(value: $0 * 7) } // Array: contains walks the elements one by one var found = queries.filter { shipped.contains($0) }.count print("array: \(found) found, \(comparisons) comparisons") // Set: one pass to build it, then one hash per lookup let shippedSet = Set(shipped) print("building the set: \(hashes) hashes") comparisons = 0 hashes = 0 found = queries.filter { shippedSet.contains($0) }.count print("set: \(found) found, \(hashes) hashes, \(comparisons) comparisons")
Output
Both searches find the same 500 orders. The array needs 3373750 comparisons, more than 3,000 per lookup, because each of the 500 misses compares against all 5,000 elements. Building the set costs 5000 hashes once; after that, the 1,000 lookups take 1000 hashes and about 2,000 comparisons, roughly two per lookup against the elements stored at or next to the hashed slot. That last number changes from run to run (one run here printed 2032 comparisons), because Swift seeds its hashing randomly each time a program starts. Build the set once, outside the loop: calling Set(array) for every lookup would hash all 5,000 elements each time.
7Which should you use?
| Method | Returns | Element type | Best for |
|---|---|---|---|
| array.contains(x) | Bool | Equatable | Is this exact value there? |
| array.contains { … } | Bool | Any | Conditions, structs, ignoring case |
| array.first(where:) | Element? | Any | Getting the matching object |
| array.firstIndex(of:) | Int? | Equatable | The position, to update or remove it |
| allSatisfy / isSubset(of:) | Bool | Equatable / Hashable | Checking several values at once |
| Set(array).contains(x) | Bool | Hashable | Many lookups against the same large array |
Frequently asked questions
How do I check if an array does not contain a value in Swift?
Negate the call: if !fruits.contains("kiwi") { … }. For a condition, !products.contains { $0.price > 100 } is true when no element matches. Swift has no notContains method and no not in operator.
Why does contains give "missing argument label 'where:' in call"?
Because the elements are not Equatable. contains(_:) exists only for Equatable elements, so the compiler falls back to contains(where:) and complains about the label. Add : Equatable to your struct (Swift writes == when every property is Equatable), or pass a closure: points.contains { $0.x == 1 && $0.y == 2 }.
How do I find the index of an element in a Swift array?
Use firstIndex(of:) for an Equatable value or firstIndex(where:) for a condition. Both return Int?, so unwrap with if let i = colors.firstIndex(of: "green"). lastIndex(of:) finds the last match. Older answers use index(of:) or indexOf, the earlier names of the same thing. On a slice such as colors[2...], the index keeps the original array's numbering.
Is Swift array contains case-sensitive?
Yes. ["Swift"].contains("SWIFT") is false. Compare inside a closure instead: tags.contains { $0.lowercased() == search.lowercased() }, or with Foundation, tags.contains { $0.caseInsensitiveCompare(search) == .orderedSame }, which also treats "Straße" and "STRASSE" as equal on Linux here.
What is the time complexity of contains on a Swift array?
O(n): it compares elements one by one and stops at the first match, so a miss checks every element. A Set lookup is O(1) on average, and contains on a range only compares with its bounds. If you check many values against the same array, build a Set once and look up in that.
How do I check if an array contains a specific class instance?
Compare identity with === in a closure: windows.contains { $0 === editor }. Classes do not get a generated ==, and === asks whether it is the same object, not one with equal properties. If two different objects with the same data should count as a match, compare the properties instead, or make the class Equatable with your own ==.