This is a simplified version of my code but I’d like to be able to initialise an NSPredicate
from a generic KeyPath<Root, Value>
but despite persistent attempts I’ve fallen short. Can anyone help?
PS: I am aware I could alter the method to take a key: String
and have callers use #keypath(Object.property)
at the call-site but I do not want to do that, as I want to enforce a KeyPath is used for compile safety.
Attempt 1
func makeNSPredicate<Root, Value>(keyPath: KeyPath<Root,Value>, value: Value) {
NSPredicate(format: "%K == (value)", argumentArray: [keyPath])
}
Runtime error: signal SIGABRT
Attempt 2
func makeNSPredicate<Root, Value>(keyPath: KeyPath<Root,Value>, value: Value) {
NSPredicate(format: "%K == (value)", keyPath)
}
Compile error: Argument type ‘KeyPath<Root, Value>’ does not conform to expected type ‘CVarArg’
Attempt 3
func makeNSPredicate<Root, Value>(keyPath: KeyPath<Root,Value>, value: Value) {
NSPredicate(format: "%K == (value)", #keyPath(keyPath))
}
Argument of ‘#keyPath’ refers to non-‘@objc’ property ‘keyPath’