Call contains(_:): text.contains("Swift") returns true or false and needs no import. It is case-sensitive; for a case-insensitive check, import Foundation and use text.localizedCaseInsensitiveContains("swift"). To learn where the match is, use text.range(of: "Swift"), which returns nil when there is none.
A Swift String is a collection of characters, and the standard library can search it for another string directly. Older answers say you need import Foundation or an NSString cast for this; current Swift doesn't, though Foundation still adds the case- and accent-insensitive searches. The sections below cover the plain check, ignoring case and accents, finding the position, whole words with a Regex, testing several words at once, and how == compares strings, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1contains(_:)Recommended
contains(_:) takes the string to look for and returns a Bool. It compares exactly, so "swift" does not match "Swift". The same name also takes a single Character. To check only the start or the end, use hasPrefix(_:) and hasSuffix(_:). None of these need an import, and all of them work on a Substring too.
let text = "Hello, Swift world" // contains(_:) returns true or false, and is case-sensitive print(text.contains("Swift")) print(text.contains("swift")) // Negate it with ! if !text.contains("Kotlin") { print("no Kotlin here") } // A single Character works too let comma: Character = "," print(text.contains(comma)) // Only the start or the end print(text.hasPrefix("Hello")) print(text.hasSuffix("world")) print(text.hasPrefix("World")) // Substrings have the same methods let rest = text.dropFirst(7) print(rest, rest.contains("Swift")) // Every string contains the empty string print(text.contains(""))
Output
contains("Swift") prints true and contains("swift") prints false: case matters. hasPrefix("World") is false for the same reason, and because world sits at the end, not the start. dropFirst(7) returns a Substring, here Swift world, and contains works on it without converting it back to a String. The last line shows that every string contains the empty string, so contains("") is true here. Keep that in mind when the search term comes from user input, and keep reading: section 2 shows the same call returning false.
2Ignoring case and accents
The case- and accent-insensitive searches come from Foundation, so they need import Foundation. localizedCaseInsensitiveContains(_:) ignores case. localizedStandardContains(_:) ignores case and accents, the way a search box should. range(of:options:) lets you pick the rules yourself, such as [.caseInsensitive, .diacriticInsensitive]. Lowercasing both sides works without Foundation, but accents still count then.
import Foundation let title = "Café Society: A Swift Story" // Ignore case print(title.localizedCaseInsensitiveContains("swift story")) // Plain contains is exact: "cafe" is not "Café" print(title.contains("cafe")) // Ignore case and accents, the search-box way print(title.localizedStandardContains("CAFE")) // Or choose the options yourself let options: String.CompareOptions = [.caseInsensitive, .diacriticInsensitive] print(title.range(of: "cafe", options: options) != nil) // lowercased() needs no Foundation, but the accent still counts print(title.lowercased().contains("cafe")) print(title.lowercased().contains("café")) // German: ß matches SS when case is ignored print("STRASSE".localizedCaseInsensitiveContains("straße")) // With Foundation imported, contains("") is false print(title.contains(""))
Output
localizedCaseInsensitiveContains finds swift story, while plain contains("cafe") prints false because of the accent and the capital C. localizedStandardContains("CAFE") and the hand-picked options both print true. Lowercasing alone gives false for cafe and true for café: it fixes case, not accents. STRASSE matches straße because Foundation folds case by Unicode rules. The last line is a trap: with Foundation imported, contains("") prints false, the opposite of section 1, because Foundation's contains takes over the call.
3Finding where it is: range(of:)
When you need the match itself, range(of:) returns a Range<String.Index>, or nil when the text isn't there, so it doubles as the contains check. A String.Index is not an Int; distance(from:to:) turns it into a character count, and the range slices the string directly. The .backwards option finds the last match. Without Foundation, firstRange(of:) and ranges(of:) do the same job.
import Foundation let sentence = "The quick brown fox jumps over the lazy fox" // range(of:) returns the first match, or nil if let range = sentence.range(of: "fox") { let offset = sentence.distance(from: sentence.startIndex, to: range.lowerBound) print("first fox at", offset) print("after it:\(sentence[range.upperBound...])") } // .backwards finds the last match if let last = sentence.range(of: "fox", options: .backwards) { let offset = sentence.distance(from: sentence.startIndex, to: last.lowerBound) print("last fox at", offset) } // nil means not found print(sentence.range(of: "cat") == nil) // Standard library versions: firstRange(of:) and ranges(of:) print(sentence.firstRange(of: "fox") == sentence.range(of: "fox")) print("fox:", sentence.ranges(of: "fox").count) print("the:", sentence.ranges(of: "the").count)
Output
The first fox starts 16 characters in, and slicing from range.upperBound gives " jumps over the lazy fox", space included. .backwards finds the second one at 40. The firstRange(of:) check prints true: both calls return the same range. ranges(of:) counts fox: 2 but the: 1, because the capital The at the start doesn't match. Matches don't overlap: "aaaa".ranges(of: "aa") finds two, not three.
4Whole words and patterns with Regex
contains("cat") is also true for concatenate. To match a whole word, pass a Regex to contains(_:) and wrap the word in \b word boundaries. This page compiles in the Swift 5 language mode, so the literal is written #/\bcat\b/#; in Swift 6 mode you can drop the # signs. ignoresCase() makes the pattern case-insensitive, and try Regex("…") builds one from a string at run time.
let whole = #/\bcat\b/# // contains("cat") also matches inside other words let line = "Please concatenate the files" print(line.contains("cat")) print(line.contains(whole)) print("The cat sat".contains(whole)) print("The Cat sat".contains(whole.ignoresCase())) // Swift's \b follows Unicode word rules: "cat's" is one word print("the cat's toy".contains(whole)) print("the cat's toy".contains(whole.wordBoundaryKind(.simple))) // Any pattern works: four digits in a row print("order 4521 shipped".contains(#/\d{4}/#)) // A word chosen at run time: build the Regex from a string let word = "dog" let dynamic = try Regex("\\b\(word)\\b") print("hot dog stand".contains(dynamic)) print("hotdog stand".contains(dynamic))
Output
contains("cat") is true for concatenate and the regex is false; The cat sat matches, and with ignoresCase() so does The Cat sat. The surprise is cat's: Swift's \b uses Unicode word rules by default, where an apostrophe between letters doesn't end a word, so it prints false. wordBoundaryKind(.simple) switches to the rule most other regex engines use and prints true. The run-time Regex finds dog in hot dog stand but not in hotdog. Regex("…") throws on an invalid pattern, hence the try.
5Any of several words: contains(where:)
To test a list of words, turn the question around and ask the array: words.contains { text.contains($0) } is true when any word appears, and stops at the first hit. filter tells you which ones, and allSatisfy checks that every word is there. Lowercase the text once before the loop for a case-insensitive check. On the string itself, contains(where:) tests one character at a time.
let message = "Claim your FREE money now" let flagged = ["spam", "free money", "winner"] // Lowercase once, then ask the array let lower = message.lowercased() print(flagged.contains { lower.contains($0) }) // Which ones appear print(flagged.filter { lower.contains($0) }) // Every word must appear let required = ["claim", "now"] print(required.allSatisfy { lower.contains($0) }) // On a String, contains(where:) tests each Character print(message.contains(where: \.isNumber)) print("Room 101".contains(where: \.isNumber)) let vowels: Set<Character> = ["a", "e", "i", "o", "u"] print("rhythm".contains(where: vowels.contains))
Output
The array check prints true, and filter names the match: ["free money"]. Without lowercased() it would miss, because the message says FREE. allSatisfy confirms both claim and now are there. On the string, contains(where: \.isNumber) is false for the message and true for Room 101, and passing vowels.contains as the test shows that rhythm has no vowel.
6Comparing whole strings with ==
To check that two strings are the same, not that one contains the other, use ==. It is Swift's answer to Objective-C's isEqualToString:, and it compares characters, not bytes. An é can be stored as one code point (U+00E9) or as e followed by a combining accent (U+0301); text pasted from a Mac file name or a web form may use either. Swift treats the two as the same characters, in ==, contains and hasSuffix alike.
let typed = "caf\u{E9}" // é as one code point let pasted = "cafe\u{301}" // e plus a combining accent print(typed, pasted) // == compares characters, not bytes print(typed == pasted) print(typed.count, pasted.count) print(typed.utf8.count, pasted.utf8.count) print(Array(typed.utf8) == Array(pasted.utf8)) // contains and hasSuffix follow the same rule print(pasted.contains("\u{E9}")) print(pasted.hasSuffix("\u{E9}")) print(pasted.contains("e")) // == is case-sensitive: compare lowercased copies to ignore case print("Swift" == "swift") print("Swift".lowercased() == "swift".lowercased())
Output
Both strings print as café and == says true. They have the same count, 4 characters, but 5 and 6 UTF-8 bytes, so the byte arrays differ. contains and hasSuffix find the one-code-point é in the two-code-point one. contains("e") is false: the e is part of the character é, not a character of its own. == is case-sensitive, so "Swift" == "swift" is false; compare lowercased copies, or see the FAQ for Foundation's caseInsensitiveCompare.
7Which should you use?
| Method | Matches | Best for |
|---|---|---|
| text.contains("x") | Exact, case-sensitive | Most checks; no import needed |
| text.localizedStandardContains("x") | Ignores case and accents | Search boxes and filters (Foundation) |
| text.localizedCaseInsensitiveContains("x") | Ignores case | Case-insensitive checks where accents matter (Foundation) |
| text.range(of: "x") | Exact; returns the range or nil | When you need the position or the text around it |
| hasPrefix / hasSuffix | Start or end only | File extensions, URL schemes, prefixes |
| text.contains(#/\bx\b/#) | Whole words, patterns | Words, not fragments of words; digits and other patterns |
| words.contains { text.contains($0) } | Any of several | Keyword lists, blocklists |
| a == b | The whole string | Equality; Unicode-aware, case-sensitive |
Frequently asked questions
Do I need to import Foundation to use contains in Swift?
No. Since Swift 5.7 the standard library has contains(_:) for a string argument, along with firstRange(of:) and ranges(of:), so "Hello, Swift".contains("Swift") compiles with no import. Older answers that say you need Foundation, or (text as NSString).containsString(...), predate that. You still need Foundation for range(of:options:), localizedCaseInsensitiveContains and localizedStandardContains.
Why does contains("") return false?
Because Foundation is imported. Without it, the standard library answers true: every string contains the empty string. With import Foundation, Foundation's contains takes over and the same call prints false. Both results are on this page (sections 1 and 2). If the search term can be empty, decide what you want and check term.isEmpty first.
How do I get the index of a substring as an Int?
Find the range, then measure from the start: if let r = text.range(of: "fox") { let i = text.distance(from: text.startIndex, to: r.lowerBound) }. For "The quick brown fox jumps over the lazy fox" that gives 16. Swift has no indexOf that returns an Int, because a String.Index is not a position you can count to in constant time.
What is the Swift equivalent of isEqualToString?
Use ==. It compares the characters of two strings and treats canonically equivalent text as equal: "caf\u{E9}" == "cafe\u{301}" is true. Don't reach for ===; it only works on class instances, and on two strings the compiler stops with argument type 'String' expected to be an instance of a class or class-constrained type.
How do I compare two strings ignoring case?
With Foundation, "Swift".caseInsensitiveCompare("SWIFT") == .orderedSame is true. Without it, compare lowercased copies: a.lowercased() == b.lowercased(). For a contains check rather than equality, use localizedCaseInsensitiveContains(_:), or localizedStandardContains(_:) to ignore accents as well.
How do I match a word that has regex characters in it, like c++?
Escape it before you build the pattern. With Foundation, let escaped = NSRegularExpression.escapedPattern(for: "c++") gives c\+\+, and then try Regex("\\b" + escaped + "\\b") finds c++ in "I like c++ a lot". Without the escaping, + is a quantifier and the pattern means something else.