Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type AnyObject? does not conform to protocol CVarArgType?

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))
}
like image 456
aryaxt Avatar asked Apr 14 '26 08:04

aryaxt


1 Answers

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)
}
like image 187
drewag Avatar answered May 05 '26 11:05

drewag