问题描述
我正在 Swift 中扩展一个基类(我无法控制).我想提供一个类函数来创建一个子类类型的实例.需要一个通用函数.但是,像下面这样的实现不会返回预期的子类类型.
I am extending a base class (one which I do not control) in Swift. I want to provide a class function for creating an instance typed to a subclass. A generic function is required. However, an implementation like the one below does not return the expected subclass type.
class Calculator {
func showKind() { println("regular") }
}
class ScientificCalculator: Calculator {
let model: String = "HP-15C"
override func showKind() { println("scientific") }
}
extension Calculator {
class func create<T:Calculator>() -> T {
let instance = T()
return instance
}
}
let sci: ScientificCalculator = ScientificCalculator.create()
sci.showKind()
调试器将 T
报告为 ScientificCalculator
,但 sci
是 Calculator
并调用 sci.showKind()
返回常规".
The debugger reports T
as ScientificCalculator
, but sci
is Calculator
and calling sci.showKind()
returns "regular".
有没有办法使用泛型来达到预期的结果,或者它是一个错误?
Is there a way to achieve the desired result using generics, or is it a bug?
推荐答案
好的,来自开发者论坛,如果您可以控制基类,则可以实现以下解决方法.
Ok, from the developer forums, if you have control of the base class, you might be able to implement the following work around.
class Calculator {
func showKind() { println("regular") }
required init() {}
}
class ScientificCalculator: Calculator {
let model: String = "HP-15C"
override func showKind() { println("(model) - Scientific") }
required init() {
super.init()
}
}
extension Calculator {
class func create<T:Calculator>() -> T {
let klass: T.Type = T.self
return klass()
}
}
let sci:ScientificCalculator = ScientificCalculator.create()
sci.showKind()
很遗憾,如果您无法控制基类,则这种方法是不可能的.
Unfortunately if you do not have control of the base class, this approach is not possible.
这篇关于是否可以将 Swift 泛型类函数返回类型限制为同一个类或子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!