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
}
SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.
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.