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.