Check if a string contains a specific substring in Swift

In this Swift programming tutorial, you are going to see how to check if a string contains a specific substring or not.

You may need to check for a word or set of characters from a Swift string. This tutorial is going to help you with this type of task.

Checking if a substring exists in a Swift string is quite an easy task. You can do it just within a few lines of code. Below you can see the code:

import Foundation

let myString = "You have brown hair"
if myString.contains("brown") {
    print("substring exists")

After we run the code it will give the output that you can see below:

substring exists

Also, read: Get the length of a string in Swift

In the above code, we store our string in the myString literate. Then use the Swift contains method for our string to check if the specific substring or word exists or not. In our case, we want to see if brown exist in the string or not. We pass the substring as a parameter of contains method.

You can notice that the Swift contains method plays the most important role. Below is the syntax for finding if a specific substring exists in the string:


In the above syntax, the string is the string and subString is the substring that we want to find inside the string.

In our case, the code myString.contains("brown") returns boolean true as it is found brown in the string. If the substring is not found from the string, it will then return boolean false.

In our example, we are using if a statement to see if the boolean value is true or false. By doing this, we are actually finding our substring brown is in the string brown hair.