在 Swift 中的 init 之外实例化 Self

Instantiate Self outside of init in Swift

我想创建一个class,这样它的子classes在调用一个函数a之后,将接收一个Self类型的新对象。我保证,subclasses 将具有 init() 方法。

在某种程度上我想克隆对象,但实际上不止于此,因为我想创建一个具有原始值的修改后的克隆,所以我真的不想使用快速复制构造函数语法

为什么不起作用?绝对是这个:

func myCustomCopy(modificationCommand: Command) -> Test {
    let newInt = modificationCommand.execute(self.myInt)
    return Test(newInt: newInt)
}

不是我想要的。

示例:

protocol Testable {
    var myInt: Int { get set }
    init(newInt: Int)
}

class Test: Testable {
    var myInt = 10
    required init(newInt: Int) { myInt = newInt }

    func myCustomCopy(modificationCommand: Command) -> Self {
        let newInt = modificationCommand.execute(self.myInt)
        return self.init(newInt: newInt)
    }
}

您可以使用 type(of:) to access an initializer of the concrete type of the metatype. Quoting the Language Reference - Metatypes

返回的(动态类型的)元类型

Use an initializer expression to construct an instance of a type from that type’s metatype value. For class instances, the initializer that’s called must be marked with the required keyword or the entire class marked with the final keyword.

因此在您的情况下,您可以使用 self 的元类型来调用 self 具体类型的 required 初始值设定项,例如

func myCustomCopy() -> Self {
    return type(of: self).init()
}

请注意,如上引述所述,由于您使用的是非最终 class,因此初始化器必须是 required