Swift - 在基类中使用'Self'类型?

时间:2015-06-15 17:11:42

标签: ios swift

我有一个NSManagedObject子类Shop,我在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!
}

现在,我想为这个对象(以及其他对象)定义一个基类,我可以在该方法中使用类类型。现在在Objective C中,我可以在这里引用'self'来获取当前调用者的类。

    // 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!
}

如何在swift中实现这种功能?

谢谢!

1 个答案:

答案 0 :(得分:0)

通过使用swift类型来实现这一点:

    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!
}