Is it possible to restrict a Swift generic class function return type to the same class or subclass?(是否可以将 Swift 泛型类函数返回类型限制为同一个类或子类?)
问题描述
我正在 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 泛型类函数返回类型限制为同一个类或子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以将 Swift 泛型类函数返回类型限制为同一个类或子类?


基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01