Swift

Swift

Made by DeepSource

Prefer contains over range(of:) != nil and range(of:) == nil SW-P1012

Performance
Major
Autofix

Using range(of:) != nil and range(of:) == nil instead of contains can lead to slower performance and less readable code.

range(of:) returns an optional value, which means that it needs to be unwrapped to a boolean value before being used for conditional statements. The contains method, on the other hand, returns a boolean value directly, which is more efficient when it needs to be used in conditional statements.

Also, the contains method explicitly conveys the intent of checking if a string contains a substring. On the other hand, using range(of:) != nil or range(of:) == nil can be less clear and might require an extra mental effort to understand the code.

Bad Practice

let name = "John Doe"
if name.range(of: "John") != nil {
    print("Name contains John")
}
if name.range(of: "Jane") == nil {
    print("Name does not contain Jane")
}

Recommended

let name = "John Doe"
if name.contains("John") {
    print("Name contains John")
}
if !name.contains("Jane") {
    print("Name does not contain Jane")
}