(Updated for Swift 3/4 now. Solutions for earlier Swift versions
can be found in the edit history.)
You can use unsafeDowncast
to cast the return value
of NSEntityDescription.insertNewObject()
to Self
(which is the type on which the method is actually called):
extension NSManagedObject {
class func create(in context: NSManagedObjectContext) -> Self {
let classname = entityName()
let object = NSEntityDescription.insertNewObject(forEntityName: classname, into: context)
return unsafeDowncast(object, to: self)
}
// Returns the unqualified class name, i.e. the last component.
// Can be overridden in a subclass.
class func entityName() -> String {
return String(describing: self)
}
}
Then
let obj = YourEntity.createInContext(context)
works and the compiler infers the type of obj
correctly as YourEntity
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…