我试图在从Xcode的beta版更新后动态生成谓词并获得编译错误。知道问题是什么。我尝试将valueForKey的结果转换为CVarArgType而没有运气。
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))
}
答案 0 :(得分:3)
问题是managedObject.valueForKey(key)
正在返回一个可选值。您将不得不验证它是否首先返回值:
if let value = managedObject.valueForKey(key) {
var predicate = NSPredicate(format: "%K == %@", key, value )
predicates.append(predicate)
}
另一个问题是您尝试传递AnyObject作为参数。您还可以向NSObject添加一个可选的强制转换到if-let,这应该可以修复编译器错误:
if let value = user.valueForKey(key) as? NSObject {
var predicate = NSPredicate(format: "%K == %@", key, value)
}