Strings · SWIFT RECIPE

Find a substring

Check case-sensitive or case-insensitive matches.

main.swift
import Foundation
let text = "Hello, Swift!"
print(text.contains("Swift"))
print(text.range(of: "swift", options: .caseInsensitive) != nil)

How it works

contains is case-sensitive. Foundation’s range search accepts comparison options. Localized matching can be more appropriate for user-facing text.

EXPECTED OUTPUT
true
true

Keep in mind

Do not use substring matching to validate a URL host or a file path.

Read the Swift language reference