是否有可能将Swift泛型类的函数返回类型限制为相同的类或子类? [英] Is it possible to restrict a Swift generic class function return type to the same class or subclass?
问题描述
我在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
as ScientificCalculator
,但 sci
是计算器
并调用 sci.showKind()
返回regular。
The debugger reports T
as ScientificCalculator
, but sci
is Calculator
and calling sci.showKind()
returns "regular".
有没有一种方法可以使用泛型来实现所需的结果,还是一个bug?
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泛型类的函数返回类型限制为相同的类或子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!