AnyObject type? does not conform to CVarArgType protocol?

I am trying to dynamically generate a predicate and get compile error after upgrade from Xcode beta. Think about the problem. I tried to distinguish the result of valueForKey from 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))
}

      

+3


source to share


1 answer


The problem is that it managedObject.valueForKey(key)

returns an optional value. You will need to check that it returns a value first:

if let value = managedObject.valueForKey(key) {
    var predicate = NSPredicate(format: "%K == %@", key, value )
    predicates.append(predicate)
}

      



Another problem is when you are trying to pass AnyObject as a parameter. You can also add a cast option to the NSObject in 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)
}

      

+3


source







All Articles