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 泛型类函数返回类型限制为同一个类或子类?
基础教程推荐
- NSString intValue 不能用于检索电话号码 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
