String match ignoring case in a Predicate

Hi,

Overview

  • I am trying to do a string match ignoring case inside a predicate.
  • "slow car" needs to be returned when I search for "Slow Car"

Problem

  • I have tried to use regex but wholeMatch(of: regex) is not allowed in a Predicate

Question

  • How do I search for a string ignoring a case inside a predicate?

My attempt

import Foundation

print("Hello, World!")

struct Car {
    let title: String
    let price: Int
}

let filterText = "Slow CAr"

let regex = Regex<Any>(verbatim: filterText)
    .ignoresCase(true)

let predicate = #Predicate<Car> { car in
    car.title.wholeMatch(of: regex) != nil
}

let c1 = Car(title: "nice fast car", price: 100)
let c2 = Car(title: "slow car", price: 100)
let cars = [c1, c2]

do {
    let filteredCars = try cars.filter(predicate)
    print(filteredCars)
} catch {
    print(error)
}

You can use caseInsensitiveCompare (found here on Stack Overflow and here in the Apple Developer Forum):

let orderedSame = ComparisonResult.orderedSame
let predicate = #Predicate<Car> { car in
    car.title.caseInsensitiveCompare(filterText) == orderedSame
}
2 Likes

@Martin Thank you so much that is the correct solution.

Declaring the variable let orderedSame = ComparisonResult.orderedSame outside the predicate is key, using ComparisonResult.orderedSame doesn't work.

Thanks once again.