Swift: 3 Ways to Check if a String Contains a Substring

Updated: February 23, 2023 By: Khue Post a comment

This succinct, practical article walks you through 3 different approaches to checking if a string contains a substring or not. Without any further ado, let’s get started.

Using the contains() method

The contains() method is a built-in method of String type in Swift. It returns a boolean value indicating whether the given string contains the specified substring.

Example:

let str = "The sky is blue and the grass is green"
if str.contains("blue") {
    print("Substring found")
} else {
    print("Substring not found")
}

Output:

Substring found

Using the range(of:) method

The range(of:) method is another built-in method of String type in Swift. It returns an optional Range object representing the range of the specified substring in the given string or nil if the substring is not found.

Example:

import Foundation

let str = "Sling Academy provides Swift tutorials"
if str.range(of: "Sling Academy") != nil {
    print("Substring found")
} else {
    print("Substring not found")
}

Output:

Substring found

See also: Optional, Nil, and Nil Check in Swift

Using Regular Expressions

Using regular expressions can be tough in some cases, but in return, it is very flexible and powerful.

The example below demonstrates how to use regular expressions to check if a string contains a substring in Swift while ignoring case sensitivity:

import Foundation

let str = "Sling Academy is a great place to learn magic."
let subStr = "academy"
let pattern = "\\b\(subStr)\\b"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let range = NSRange(location: 0, length: str.utf16.count)

if regex.firstMatch(in: str, options: [], range: range) != nil {
    print("Substring found in string")
} else {
    print("Substring not found in string")
}

Output:

Substring found in string

In the code above, we define a regular expression pattern called pattern that matches the substring subStr, with the \b character indicating that the match should only occur at a word boundary. The NSRegularExpression class is used to compile the regular expression pattern into a regular expression object with the .caseInsensitive option set. The firstMatch(in:options:range:) method is used to search for the first match of the regular expression in the string str.