Core Data String Query Examples in Swift

This post presents NSFetchRequest examples with NSPredicates that take String arguments. Examples will be shown for the following queries:

  1. Is equal to a string
  2. Contains a string
  3. Matches regex
  4. Begins with a string
  5. Ends with a string

The examples below will query a Core Data database with a single entity description, Person. Person has a single attribute name, a String.

Exact String Match With A NSPredicate

The LIKE keyword in an NSPredicate will perform an exact string match.

let query = "Rob"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name LIKE %@", query)

// The == syntax may also be used to search for an exact match
request.predicate = NSPredicate(format: "name == %@", query)

Additionally, the c and d modifiers can be used to perform a case-insensitive and diacritic insensitive (c would match ç as well) search:

let query = "Rob"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name LIKE[cd] %@", query)

Contains String With A NSPredicate

The CONTAINS keyword in an NSPredicate will perform a contains string match.

let query = "Rob"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name CONTAINS %@", query)

The c and d modifiers can also be used with CONTAINS to perform a case-insensitive. and diacritic insensitive (c would match ç as well) search.

The MATCHES keyword in an NSPredicate is used to perform a regular expression search.

let query = "??bert*"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name MATCHES %@", query)

Search For Matches That Begin With String

The BEGINSWITH keyboard in an NSPredicate is used to perform a search for strings that begin with a specific substring.

let query = "R"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name BEGINSWITH %@", query)

Search For Matches That End With String

The ENDSWITH keyboard in an NSPredicate is used to perform a search for strings that end with a specific substring.

let query = "R"
let request: NSFetchRequest<Person> = Person.fetchRequest()
request.predicate = NSPredicate(format: "name BEGINSWITH %@", query)

Find Strings In Core Data

That’s it! With LIKE, CONTAINS, MATCHES, BEGINSWITH, and ENDSWITH you can perform a wide array of queries in Core Data with String arguments.