I'm trying to create a Generic function in a class extension, but I get compiler error.
I have too classes A and B, both extending NSManagedObject
I want to create a findOne()
function in my class extension.
extension NSManagedObject {
public class func findOne() -> NSManagedObject {
// some working stuff returning a NSManagedObject
}
}
My problem is : When I use this method on A, the return type is NSManagedObject
let aObject = A.findOne //type is NSManagedObject
So, obviously I can cast it and get an A-class object
let aObject = A.findOne as! A//type is NSManagedObject
Starting here, I want to replace my extension implementation to use generic, making me have :
let aObject = A.findOne //type is A
I tried this :
extension NSManagedObject {
public class func findOne<T>() -> T {
// some working stuff returning a NSManagedObject
}
}
But A.findOne()
is still NSManagedObject
type.
Can anyone help me ?
UPDATE The Following code is actually working if I use :
class func findOne<T : NSManagedObject>() -> T {
//Do some stuff
return myObject as! T
}
let myObject : A = A.findOne()