Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot override initializer of NSDictionary in Swift

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")
    }
}
like image 401
Mel Avatar asked Sep 28 '22 17:09

Mel


1 Answers

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

like image 178
Hadi.M Avatar answered Nov 13 '22 01:11

Hadi.M