【问题标题】:self class alloc equivalent in SwiftSwift 中的 self 类分配等价物
【发布时间】:2016-02-24 02:07:19
【问题描述】:

我有一个用 Objective-C 编写的模型类,它应该被子类继承。有一个方法:

- (id)deepcopy {
    id newModel = [[[self class] alloc] init];
    newModel.id = self.id;
    // do something
    return newModel;
}

子类应该用类似的东西覆盖它:

- (id)deepcopy {
    id newModel = [super deepcopy];
    // something else
    return newModel;
}

关键是[[[self class] alloc] init],它将根据实际类实例化一个对象。最近我尝试将这个项目升级到 Swift,但找不到在 Swift 中做同样事情的方法。

我该怎么做?

【问题讨论】:

  • 好问题!对于继承单例 sharedInstance 样式的 getter 也很有用

标签: ios objective-c swift


【解决方案1】:

我想你要找的是dynamicType:

func deepcopy() -> Self {
    let newModel = self.dynamicType.init()
    return newModel
}

更新至于 Swift 3,这似乎可行:

func deepcopy() -> Self {
    let newModel = type(of: self).init()
    return newModel
}

【讨论】:

  • 感谢您的帮助!这个我早试过了,但是报错了,我还以为不对。现在我发现这是由于其他原因。
  • 当尝试在UIViewController 的子类上使用它时,我收到以下错误:Type 'MyViewController.Type' has no member 'init' 知道有什么问题吗?我正在编写 Swift 3。
  • @Banana : 请帮我解决同样的问题
  • @Banana 制作所需的初始化程序。
猜你喜欢
  • 1970-01-01
  • 2019-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 2014-11-23
相关资源
最近更新 更多