Swift – Check if String Contains Another String

To check if a String str1 contains another String str2 in Swift, use String.contains() function. Call contains() function on str1 and pass str2 as argument.

The syntax to check if String str1 contains the String str2 is

</>
Copy
str1.contains(str2)

contains() function returns a boolean value. If string str1 contains the string str2 , then the function returns true, else the function returns false.

Note: Make sure to import Foundation.

Example

In this example, we will take two string in variables str1 and str2. Using String.contains() function, we will check if the string str1 contains the string str2.

main.swift

</>
Copy
import Foundation

var str1 = "Hello World"
var str2 = "Wor"
var result = str1.contains(str2)
print("Does str1 contain str2 : \(result)")

Output

Does str1 contain str2 : true

Now, we will take different values for str1 and str2, such that str1 does not contain str2, and check the result of contains() function.

main.swift

</>
Copy
import Foundation

var str1 = "Hello World"
var str2 = "AAA"
var result = str1.contains(str2)
print("Does str1 contain str2 : \(result)")

Output

Does str1 contain str2 : false

Conclusion

In this Swift Tutorial, we learned how to check if a string another another string using String.contains() function.