0

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()
CZ54
  • 5,488
  • 1
  • 24
  • 39
  • you might want to use `Self` as return type. – luk2302 May 18 '16 at 12:40
  • Compare [How can I create instances of managed object subclasses in a NSManagedObject Swift extension?](http://stackoverflow.com/questions/27109268/how-can-i-create-instances-of-managed-object-subclasses-in-a-nsmanagedobject-swi). – Martin R May 18 '16 at 12:44
  • @Alessandro: Why did you add "OS X" in the title and the tags? Core Data exists on iOS as well, and nothing in this question is specific to OS X. – Martin R May 18 '16 at 13:23
  • @Martin R NSManagedObject exist on both iOS and OSX , i want to add just only on the tag. On title is my wrong specification. – Alessandro Ornano May 18 '16 at 13:35

1 Answers1

0

You can create a BaseModel, which all your models inherit from. Use the generic type parameter to cast the object accordingly

class BaseModel : NSManagedObject {

    class func find<T>(objectID: NSManagedObjectID) -> T
    {
        return someObjectContext.objectWithID(objectID) as! T
    }
}

class Person : BaseModel {

}


let person: Person = Person.find(someObjectId)

Generics

Laffen
  • 2,753
  • 17
  • 29
  • Both A and B are extending `NSManagedObject` so your answer does not resolve my problem :( – CZ54 May 18 '16 at 12:53