Goodbye NSPredicate, hello Realm Swift Query API
Rate this announcement
I'm not a fan of writing code using pseudo-English text strings. It's a major context switch when you've been writing "native" code. Compilers don't detect errors in the strings, whether syntax errors or mismatched types, leaving you to learn of your mistakes when your app crashes.
I spent more than seven years working at MySQL and Oracle, and still wasn't comfortable writing anything but the simplest of SQL queries. I left to join MongoDB because I knew that the object/document model was the way that developers should work with their data. I also knew that idiomatic queries for each programming language were the way to go.
That's why I was really excited when MongoDB acquired Realm—a leading mobile object database. You work with Realm objects in your native language (in this case, Swift) to manipulate your data.
However, there was one area that felt odd in Realm's Swift SDK. You had to use
NSPredicatewhen searching for Realm objects that match your criteria.
NSPredicates are strings with variable substitution. 🤦♂️
NSPredicates are used when searching for data in Apple's Core Data database, and so it was a reasonable design decision. It meant that iOS developers could reuse the skills they'd developed while working with Core Data.
But, I hate writing code as strings.
The good news is that the Realm SDK for Swift has added the option to use type-safe queries through the Realm Swift Query API. 🥳.
You now have the option whether to filter using
or with the new Realm Swift Query API:
In this article, I'm going to show you some examples of how to use the Realm Swift Query API. I'll also show you an example where wrangling with
NSPredicatestrings has frustrated me.
I have a number of existing Realm iOS apps using
NSPredicates. When I learnt of the new query API, the first thing I wanted to do was try to replace some of "legacy" queries. I'll start by describing that experience, and then show what other type-safe queries are possible.
I'll start with the example I gave in the introduction (and how the
NSPredicateversion had previously frustrated me).
- Whether you have the option to split your hand (you've been dealt two cards with the same value)
- Your hand is "soft" (you've been dealt an ace, which can take the value of either one or eleven)
- Any other hand
But, what if I'd mistyped the attribute name? There's no Xcode auto-complete to help when writing code within a string, and this code builds with no errors or warnings:
When I run the code, it works initially. But, when I'm dealt a soft hand, I get this runtime crash:
Rather than having a dedicated view for each of the three types of hand, I want to experiment with having a single view to handle all three.
SwiftUI doesn't allow me to use variables (or even named constants) as part of the filter criteria for
@ObservedResults. This is because the
structhasn't been initialized until after the
@ObservedResultsis defined. To live within SwitfUIs constraints, the filtering is moved into the view's body:
Again, this builds, but the app crashes as soon as I'm dealt a soft hand. This time, the error is much more cryptic:
It turns out that, you need to convert the boolean value to an
NSNumberbefore substituting it into the
Who knew? OK, StackOverflow did, but it took me quite a while to find the solution.
Hopefully, this gives you a feeling for why I don't like writing strings in place of code.
This is the same code using the new (type-safe) Realm Swift Query API:
The code's simpler, and (even better) Xcode won't let me use the wrong field name or type—giving me this error before I even try running the code:
Again, I find this more Swift-like, and bugs will get caught as I type/build rather than when the app crashes.
I'll use this simple
Objectto show a few more example queries:
All in-progress tasks assigned to name:
All tasks where the
priorityis higher than
All tasks that have a
prioritythat's an integer between
All tasks where the
assigneename string includes
You may need to filter your Realm objects on values within their sub-objects. Those sub-object may be
EmbeddedObjects or part of a
I'll use the
Projectclass to illustrate filtering on the attributes of sub-documents:
All projects that include a task that's in-progress, and is assigned to a given user:
You can include the where modifier directly in your
@ObservedResultscall. That avoids the need to refine your results inside your view's body:
Unfortunately, SwiftUI rules still mean that you can't use variables or named constants in your
Realm type-safe queries provide a simple, idiomatic way to filter results in Swift. If you have a bug in your query, it should be caught by Xcode rather than at run-time.
For those that prefer working with
NSPredicates, you can continue to do so. In fact the Realm Swift Query API runs on top of the
NSPredicatefunctionality, so they're not going anywhere soon.