Core Data String Queries Using NSPredicate In Swift

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

  1. Exact String Match With A NSPredicate
  2. Contains String With A NSPredicate
  3. NSPredicate Regex Search
  4. Search For Matches That Begin With String
  5. Search For Matches That End With String

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

FREE all Swift loading animations.

Loading Animation Example

Follow AdvancedSwift and immediately get access to commented code for these animations that you can use in your projects.

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.