获得超类的克隆 [英] Getting clone of superclass

查看:62
本文介绍了获得超类的克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的游乐场摘要:

class Box {
  func clone() -> Box {
    return Box() // <- how to return superclass here?
  }
}

class VBox:Box { }

let vb = VBox()
let cBox = vb.clone() // now cBox is a Box, not a VBox

我的克隆函数在所有情况下均返回 Box 类。但是对于子类,我希望它返回超类(因此在其上面应该返回 VBox )。

My clone function returns a Box class in all cases. But for the subclass I want it to return the superclass (so above it should return VBox).

我知道我可以覆盖 clone 函数 VBox ,但我想知道是否有更聪明的方法。

I know I could override the clone function inside VBox but I wonder if there's a smarter way.

推荐答案

您的意思是子类。 Box是超类,这是您要返回的内容。

You mean subclass. Box is the superclass, which is what you're returning.

这与以下内容非常相似:

This is very similar to the following:

  • Protocol func returning Self
  • Swift protocol and return types on global functions

但是,这并不是一个完全相同的问题,因为您是在处理类而不是协议,所以我们可以解决这个问题例。首先,正确的工具是 init ,而不是 clone

It's not exactly the same question, though, since you're dealing with classes rather than protocols, so we can go through that example. First, the right tool is init, not a clone:

class Box {
    let a: String
    init(_ a: String) { self.a = a }
    convenience init(copy: Box) { self.init(copy.a) }
}

class VBox:Box {}

let vb = VBox("test")
let cBox = VBox(copy: vb)

您看到,由于 VBox 不添加任何其他属性。但是,如果 VBox 确实添加了其他属性,那么您将得到所有正确的错误,这些错误要求您实施 init

You see that this works fine since VBox adds no additional properties. But if VBox does add additional properties, then you'll get all the right errors that require you to implement an init.

class Box {
    let a: String
    init(_ a: String) { self.a = a }
    convenience init(copy: Box) { self.init(copy.a) }
}

class VBox:Box {
    let b: String
    init(_ a: String, _ b: String) {
        self.b = b
        super.init(a)
    }
    convenience init(copy: VBox) {
        self.init(copy.a, copy.b)
    }
}

let vb = VBox("test", "this")
let cBox = VBox(copy: vb)

请注意这如何阻止您尝试将 Box 复制到 VBox (因为这不会初始化所有参数)。如果您希望这样做,则需要提供一个 copy(Box)初始化程序。这是关于使用 init 的好处。它会为您跟踪所有规则。 NSCopying 会让您犯该错误,并最终导致崩溃。

Note how this prevents you from trying to copy a Box into a VBox (since that would not initialize all the parameters). If you want that to work, you'd need to provide a copy(Box) initializer. This is the nice thing about using init. It keeps track of all the rules for you. NSCopying would let you make that mistake and would eventually crash.

这篇关于获得超类的克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆