问题
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' 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
Is there any way to override the initializer of NSDictionary or can Swift just not handle that yet?
Here's my class:
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")
}
}
回答1:
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):
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.
Check https://github.com/ksm/SwiftInFlux/blob/master/README.md#overriding-declarations-from-extensions
来源:https://stackoverflow.com/questions/28636598/cannot-override-initializer-of-nsdictionary-in-swift