How to check if a string contains a substring in Swift with example
This tutorial explains how to check substring exists in a string in swift with examples
For example, If a given string is cloudhadoop, substring cloud returns true.
How to check if a string contains a substring in Swift?
- use contains in Swift 4 & 5 versions
The string has contain a method that takes substring and returns true if found, else returns false.
It does not check case sensitive substrings
import Foundation
let string = "cloudhadoop"
print (string.contains("cloud")) //true
print (string.contains("Cloud")) //false
if string.contains("cloud") {
print("Substring Found")
}
Output:
true
false
Substring Found
- use range in swift 3 and older version
String range function returns non-nil value if found, else return nil
.
import Foundation
let str = "cloudhadoop"
print(str.range(of:"cloud") )
print(str.range(of:"Cloud") )// returns nil
if str.range(of:"cloud") != nil {
print("Substring Found")
}
Output:
Optional(Range(Swift.String.Index(_rawBits: 1)..<Swift.String.Index(_rawBits: 327680)))
nil
Substring Found