{

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
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.