#22: Check if a String Contains Another String in Swift

If you only need a yes/no answer, contains is the easiest option:

let text = "Swift bites are short and useful"
text.contains("short") // true

If you also need options such as case-insensitive matching or the position of the match, use range(of:):

let found = text.range(of: "SWIFT", options: .caseInsensitive) != nil
// true

range(of:) is the more flexible API, while contains is great when readability matters most.


I'm also on Twitter and GitHub.

Subscribe via RSS.