How do I check if a string contains a pattern?

Asked on 2024-07-30

1 search

To check if a string contains a pattern in Swift, you can use the contains method. This method is demonstrated in the context of Swift testing, where it is used to verify conditions in tests. Here's an example of how you might use it:

let string = "Hello, World!"
let pattern = "World"
let containsPattern = string.contains(pattern)
print(containsPattern) // This will print 'true' if the pattern is found in the string

Additionally, if you are dealing with localized strings and need to respect locale-specific conventions, you can use the localizedStandardRange method. This method is particularly useful for handling different spelling conventions across various languages.

For more details on using contains in the context of Swift testing, you can refer to the session Meet Swift Testing (04:45).