I am trying to dynamically generate a predicate and getting a compile error after updating from beta version of Xcode. Any idea what the problem is. I tried casting the result of valueForKey to CVarArgType with no luck.
import UIKit
import CoreData
class User: NSManagedObject {
@NSManaged var a: String?
@NSManaged var b: String?
}
var user = User() // This will probably crash, but good enough to reproduce compile error
var keys = ["a", "b"]
for key in keys {
var predicate = NSPredicate(format: "%K == %@", key, user.valueForKey(key))
}
The problem is that managedObject.valueForKey(key) is returning an optional value. You are going to have to validate that it is returning a value first:
if let value = managedObject.valueForKey(key) {
var predicate = NSPredicate(format: "%K == %@", key, value )
predicates.append(predicate)
}
The other problem is that you are trying to pass an AnyObject as the parameter. You can also add an optional cast to NSObject to the if-let and that should fix your compiler error:
if let value = user.valueForKey(key) as? NSObject {
var predicate = NSPredicate(format: "%K == %@", key, value)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With