Enhancement Request: NSPredicates with Swift KeyPaths

Number:rdar://46479060 Date Originated:05-Dec-2018 08:45 AM
Status:Open Resolved:
Product:iOS + SDK Product Version:12.1
Classification:Enhancement Reproducible:Always
NSPredicates currently only support passing in strings with formatted values. There is not presently a compile-time way to validate that: 

a) The key you’re looking for even exists on the thing you’re using the predicate to find
b) The name of the key hasn’t changed
c) The name of the key is spelled the same as the actual property*
d) The value you’re searching for is actually a valid one for the expected type

This leads to stuff like `NSPredicate(format: “value == 1”), which is extremely fragile, and super easy to screw up without realizing it. 

Adding KeyPath support to NSPredicate would allow type-safe querying, particularly with but not limited to CoreData. I pulled together something (and tested the crap out of it) that seems to do this pretty well: https://github.com/UseSweet/SweetFoundation/pull/34 but have been directed to Radar rather than open-source since this is an Apple-owned API. 

Can we have this please? :)

*- I am partial to this reason because I am an absolutely garbage speller, but this would also help developers who are developing in a language that is not their primary language.

Steps to Reproduce:
1. Use NSSortDescriptor with Swift KeyPaths, rejoice at not having to have Stringly-typed code anymore
2. Try to use NSPredicate with Swift KeyPaths, realize that doesn’t exist
3. Have sad

Expected Results:
Ability to use a Predicate something like `NSPredicate(keyPath: \Object.isSomething, operatorType: .equals, value: true)`, where the predicate validates that the value of the object at the keyPath `isSomething` actually is a boolean. 

Actual Results:
`NSPredicate(“isSomething == 1”)` instead of something type safe.


Again, my stab at doing this open source: https://github.com/UseSweet/SweetFoundation/pull/34
That’s based on Katsuwi Kishikama’s Kuery, but stripped of any dependencies on core data: https://github.com/kishikawakatsumi/Kuery

Other things I’ve found: 
Existing Swift bug: https://bugs.swift.org/browse/SR-5220
Stab someone took at a spec on adding Predicates to Swift: https://bugs.swift.org/browse/SR-5220


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!