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

标签 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 中实现这种功能?

谢谢!

最佳答案

通过使用像这样的 swift Types 来让它工作:

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

关于ios - Swift - 在基类中使用 'Self' 的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851042/

相关文章:

ios - iPhone 5 armv7s 处理器与其前代产品有何不同?

ios - 从 UITableView 中的 UI 中删除标题和相应的单元格

swift - 将选择器添加到 UIStepper 的 addTarget 函数时出错 - Swift 3

objective-c - Model View Controller : Does the Controller or Model fetch data off the server?

ios - XCTAssertTrue 在测试 iOS UI 时不会失败

ios - Google Analytics Pod 安装了太多依赖项

ios - 带有搜索按钮的 UISearchController 栏向错误的方向增长

swift - 如何使 Int 符合 BinaryFloatingPoint 或 Double/CGFloat 符合 BinaryInteger?

ios - Swift 单选按钮不可点击

ios - 如何使用 segue 为 Facebook iOS Friend Picker 自定义背景和单元格?