Sebastian Faltoni Software Architect. Passionate about Clean Code, Tech, Web, AI, .NET, Python, IOT, Swift, SwiftUI and also Blazor

How to use KeyPath on CoreData Predicate for easy refactoring and preventing mistakes

37 sec read

If you come from a C# background for example you could be looking for something similar to nameof(Page.name)on Swift.

If instead of hard-coded strings we could use something that retrieves our property’s names directly from our type, we can avoid errors caused by mistyping a name, or when for example we remove a property or renaming it during development.

We can achieve something very similar to nameof for Predicates, take as an example the following snippet.

NSPredicate(format: "%K == %@",#keyPath(Page.parent), NSNull())

In the above example, inside the format string %K is used as a placeholder for the keyPath and %@ the value. We have replaced a hard-coded string with a keyPath expression, so when, for example, we remove the parent property from our model, it won’t compile.

We can do the same for multiple parameters.

NSPredicate(format: "%K == %@ AND %K == %@", #keyPath(Page.parent), NSNull(), #keyPath(Page.title), "Nuova nota")

If you check the type on XCode you’ll notice that #keyPath(Page.title) returns a string.

References

Sebastian Faltoni Software Architect. Passionate about Clean Code, Tech, Web, AI, .NET, Python, IOT, Swift, SwiftUI and also Blazor

A simple extension to use Combine with PromiseKit and…

Because ServiceStack use PromiseKit for it’s async calls on Swift, i made this little extension that convert a PromiseKit request into a Combine publisher....
Sebastian Faltoni
39 sec read

Leave a Reply

Your email address will not be published. Required fields are marked *