0

I've got a NSManagedObject subclass Shop for which I have defined the following function in swift:

    // insertions
public class func insertOrUpdateRepresentation(representation: Dictionary<String, AnyObject>, context: NSManagedObjectContext) -> Shop {

    let identifier = representation["id"] as! NSNumber
    let string = identifier.stringValue
    var shop = Shop.fetchObjectWithIdentifier(string, context: context) as! Shop?

    // insert if needed
    if (shop == nil) {
        shop = NSEntityDescription.insertNewObjectForEntityForName(Shop.entityName(), inManagedObjectContext: context) as? Shop
    }

    // update
    shop?.deserializeRepresentation(representation)
    return shop!
}

Now, I'd like to define a base class for this object (and others) where I can use the class type in that method. Now in Objective C, I could reference 'self' here to get the current caller's class.

    // insertions
public class func insertOrUpdateRepresentation(representation: Dictionary<String, AnyObject>, context: NSManagedObjectContext) -> MyManagedObject {

    let identifier = representation["id"] as! NSNumber
    let string = identifier.stringValue
    var obj = (class of the caller).fetchObjectWithIdentifier(string, context: context) as! (class of the caller)?

    // insert if needed
    if (obj == nil) {
        obj = NSEntityDescription.insertNewObjectForEntityForName((class of the caller).entityName(), inManagedObjectContext: context) as? (class of the caller)
    }

    // update
    obj?.deserializeRepresentation(representation)
    return obj!
}

How do I implement this kind of functionality in swift?

Thanks!

Sean Danzeiser
  • 9,141
  • 12
  • 52
  • 90

1 Answers1

0

Got this to work by using swift Types like so:

    public class func insertOrUpdateRepresentation<T: DDManagedObject>(representation: Dictionary<String, AnyObject>, context: NSManagedObjectContext, type: T.Type) -> T {

    let identifier = representation["id"] as! NSNumber
    let string = identifier.stringValue
    var obj = T.fetchObjectWithIdentifier(string, context: context) as! T?

    // insert if needed
    if (obj == nil) {
        obj = NSEntityDescription.insertNewObjectForEntityForName(T.entityName(), inManagedObjectContext: context) as? T
    }

    // update
    obj?.deserializeRepresentation(representation)
    return obj!
}
Sean Danzeiser
  • 9,141
  • 12
  • 52
  • 90
  • ya seems to work ... although I'm very new to swift so I might be doing lots wrong. What looks suspicious to you? – Sean Danzeiser Jun 15 '15 at 19:02
  • Any time you force unwrapping or casting (`as!` or `obj!`) you are potentially asking for trouble later... – matt Jun 15 '15 at 19:58