无法在 Swift 中覆盖 NSDictionary 的初始值设定项 [英] Cannot override initializer of NSDictionary in Swift
问题描述
我正在尝试扩展 Swift 中的类 NSDictionary 以包含在 init() 上设置的 NSDate.当我添加自定义 init() 时,出现编译器错误:
I'm trying to extend the class NSDictionary in Swift to contain an NSDate that is set on init(). When I add my custom init(), I get the complier error:
'required' 初始值设定项 'init(dictionaryLiteral:)' 必须由'NSDictionary' 的子类
'required' initializer 'init(dictionaryLiteral:)' must be provided by subclass of 'NSDictionary'
但是,当我使用自动完成添加该初始化程序时,出现以下错误:
However, when I add that initializer using auto-complete, I get the following error:
来自扩展的声明还不能被覆盖
Declarations from extensions cannot be overridden yet
有什么方法可以覆盖 NSDictionary 的初始值设定项,或者 Swift 还不能处理吗?
Is there any way to override the initializer of NSDictionary or can Swift just not handle that yet?
这是我的课程:
class DateParam : NSDictionary {
let date : NSDate
init(date: NSDate) {
super.init()
self.date = date
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required convenience init(dictionaryLiteral elements: (NSCopying, AnyObject)...) {
fatalError("init(dictionaryLiteral:) has not been implemented")
}
}
推荐答案
Swift 有官方的扩展机制来向类添加方法,但是当子类覆盖扩展方法时编译器会报错.不过,错误文本看起来很有希望(强调):
Swift has an official extension mechanism for adding methods to classes, but the compiler kicks up an error when a subclass overrides an extension method. The error text looks hopeful, though (emphasis added):
来自扩展的声明不能被覆盖正是这种悬而未决的尚未"鼓励我相信 Apple 的工程师已经意识到诸如受保护扩展模式之类的设计模式,并将更新 Swift 以支持它们.
Declarations from extensions cannot be overridden yet It’s that dangling "yet" that encourages me to believe that Apple’s engineers are aware of the design patterns like the protected extension pattern and will update Swift to support them.
检查https://github.com/ksm/SwiftInFlux/blob/master/README.md#overriding-declarations-from-extensions
这篇关于无法在 Swift 中覆盖 NSDictionary 的初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!