I have this piece of code which was working ok in XCode6 (Swift 1.2) but not with the 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
}
}
Error shows on the line containing object.setValue with the message:
Ambiguous use of 'setValue(_:forKey:)'
I think it does not recognise object to be of NSManagedObject type but I'm not 100% sure, any clue why this happens much appreciated.
I've posted same question on Apple Forum and got an answer with 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've submitted a bug report to Apple as well.
One more possible solution is this:
(object as NSManagedObject).setValue(value, forKey: attribute)
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