Swift version: 5.6
You can search for one string inside another using the range(of:)
method, like this:
let string = "The rain in Spain"
let range1 = string.range(of: "rain")
That returns an optional string index: if the word was found it will say where it was found, otherwise it will be nil.
However, range(of:)
does a case-sensitive search by default, which means it will match “rain” but not “Rain” or “RAIN”. If you want a case-insensitive search you need to provide an extra parameter called options
, passing it .caseInsensitive
:
let range2 = string.range(of: "rain", options: .caseInsensitive)
That returns the same optional value depending on what was found, so you can wrap the whole thing in an if let
to see whether a match was found:
if let range3 = string.range(of: "rain", options: .caseInsensitive) {
// match
} else {
// no match
}
SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!
Sponsor Hacking with Swift and reach the world's largest Swift community!
Available from iOS 8.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.