String.hasPrefix() / hasSuffix() / contains()
In Swift strings, you can check the beginning or end with hasPrefix() and hasSuffix(), and test whether a string contains a specific substring or matches a condition using contains().
Syntax
// Prefix match
string.hasPrefix("prefix")
// Suffix match
string.hasSuffix("suffix")
// Substring match
string.contains("search string")
// Range search
string.range(of: "search string")
// Case-insensitive search
string.localizedStandardContains("search string")
Method List
| Method | Description |
|---|---|
| string.hasPrefix(string) | Returns a Bool indicating whether the string begins with the specified string. |
| string.hasSuffix(string) | Returns a Bool indicating whether the string ends with the specified string. |
| string.contains(string) | Returns a Bool indicating whether the string contains the specified string. |
| string.range(of: string) | Returns the range (Range<Index>) of the first match, or nil if not found. |
| string.range(of: string, options: .caseInsensitive) | Performs a case-insensitive range search. |
| string.localizedStandardContains(string) | Performs a locale-aware, case-insensitive substring search. |
| string.firstRange(of: regex) | Returns the range of the first match for a regular expression (Swift 5.7 and later). |
Sample Code
// hasPrefix and hasSuffix
let filename = "report_2026.pdf"
print(filename.hasPrefix("report")) // true
print(filename.hasSuffix(".pdf")) // true
print(filename.hasSuffix(".txt")) // false
let url = "https://example.com/page"
if url.hasPrefix("https://") {
print("Secure connection")
}
// contains
let message = "Swift is a type-safe language"
print(message.contains("type-safe")) // true
print(message.contains("dynamically typed")) // false
// Getting the position with range(of:)
let text = "Hello, World!"
if let range = text.range(of: "World") {
print("Found: \(text[range])")
// Get the substring after the match
print("Remainder: \(text[range.upperBound...])")
}
// Case-insensitive search
let html = "<a href='Link?lang=en'>text</a>"
if html.range(of: "link", options: .caseInsensitive) != nil {
print("'link' found (case-insensitive)")
}
// Filtering multiple files
let files = ["photo.jpg", "doc.pdf", "image.png", "report.pdf", "video.mp4"]
let pdfs = files.filter { $0.hasSuffix(".pdf") }
print(pdfs) // ["doc.pdf", "report.pdf"]
Notes
hasPrefix, hasSuffix, and contains all handle Unicode correctly and perform locale-independent comparisons. To ignore case, use range(of:options:.caseInsensitive) or localizedStandardContains.
range(of:) returns a Range<String.Index> for the matched position. Swift string indices are of type String.Index, not Int. You cannot access characters using integer offsets directly.
For string replacement and trimming, see string.replacingOccurrences() / trimmingCharacters().
If you find any errors or copyright issues, please contact us.