NSManagedObject.setValue (value: AnyObject ?, forKey key: String) causes an error in Swift 2.0

I have this piece of code that works fine in Xcode6 (Swift 1.2) but not with Swift 2:

class func findOrCreate<T: NSManagedObject>(type: T.Type, attribute: String, value: AnyObject?) -> T { if let object = T.MR_findFirstByAttribute(attribute, withValue: value) as? T { return object } else { let object = T.MR_createEntity() as! T if let value:AnyObject = value { object.setValue(value, forKey: attribute) } return object } } 

The error appears in the line containing object.setValue, with the message:

Ambiguous use of 'setValue (_: forKey :)'

I think that it does not recognize an object of type NSManagedObject, but I'm not 100% sure, suggesting why this is very much appreciated.

+6
source share
2 answers

I posted the same question on the Apple Forum and got the answer in a workaround for this problem:

  let object = T.MR_createEntity() as! NSManagedObject if let value:AnyObject = value { object.setValue(value, forKey: attribute) } return object as! T 

This works as expected. I also sent an error report to Apple.

+6
source

Another possible solution:

 (object as NSManagedObject).setValue(value, forKey: attribute) 
+4
source

All Articles