Checking if a Swift String contains a certain text
Last Run on XCODE 11.4 / Swift 5.2
A simple way to check if a string contains a certain text is to use the method contains
available to Strings.
In the code snippet below, we will check if a string contains a certain text.
let fruit1 = "apple"
let fruit2 = "banana"
let mySentence = "An apple a day keeps the doctor away."
mySentence.contains(fruit1) // result --> True
mySentence.contains(fruit2) // result --> False
If we need to check the string against multiple options, we will have
to use a variation of the contains
method that takes a closure. Checkout the code snippet below.
let fruits1 = ["apple", "bananas", "grapes"]
let fruits2 = ["bananas", "grapes"]
let mySentence = "An apple a day keeps the doctor away."
fruits1.contains(where: mySentence.contains) // result --> True
fruits2.contains(where: mySentence.contains) // result --> False