Cannot override initializer of NSDictionary in Swift

这一生的挚爱 提交于 2019-12-10 14:41:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!