Skip to main content

What to do when you want to filter a Realm object, using NSPredicate in SwiftUI or in Swift.  

Applying the filter to a simple condition in one line

let exists = realm.objects(ExampleObj.self).filter(NSPredicate(format: "uid = %ld", uid))

Creating a variable predicate that will be injected as a condition

let predicate = NSPredicate(format: "uid = %ld AND nid = %ld",uid,nid)

let exists = realm.objects(ExampleObj.self).filter(predicate)

Finally, managing the predicate as an array by using the NSCompoundPredicate.  Great when flags can be check for applying the condition.

Use NSCompoundPredicate to create an AND or OR compound predicate of zero or more other predicates.  For more details see the Apple developers page.

var predicate: [NSPredicate] = []
// initial condition
let namePredicate = NSPredicate(format: "name = %ld", name)
predicate.append(namePredicate)
// if the uid is set to greater than zero, then add the condition to the query
if uid > 0 {
  let uidPredicate = NSPredicate(format: "uid = %ld", uid)
  predicate.append(uidPredicate)
}
// compound the conditions
let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicate)
let exists = realm.objects(ExampleObj.self).filter(compoundPredicate)
Predicate syntax

%@ is a var arg substitution for an object value—often a string, number, or date.

String comparisons

By way of example, use the string comparisons such as:

NSPredicate(format: "firstName BEGINSWITH[c] %@", firstname))

In the query above use if you want to ignore case you need by adding [c]

BEGINSWITH: The left-hand expression begins with the right-hand expression.
CONTAINS: The left-hand expression contains the right-hand expression.
ENDSWITH: The left-hand expression ends with the right-hand expression.
LIKE: The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.
MATCHES: The left hand expression equals the right hand expression using a regex-style comparison 

Related articles

Andrew Fletcher12 Aug 2022
Using SwiftUI URLComponent to change a URL's scheme
The challenge I was facing, I had written a script to scan barcodes and use Google book API to view the contents.  However, a snippet of the JSON response { "contentVersion": "0.2.0.0.preview.0", "panelizationSummary": { "containsEpubBubbles": false, ...