Swift: Subclassing NSNotification

Hello everyone,


Has anyone figured out a way to subclass NSNotification using Swift? I've done this in the past with Objective-C, but haven't figured out how to accomplish this with the rules for initializers in Swift. I realize there are alternatives to subclassing, but I'd really like to figure out how to do this. Here is a simplified version of what I'm attempting to do:


class MyNotification: NSNotification {

    var someCustomData: String = ""

    override var name: String {
        return ""
    }

    override var object: AnyObject? {
        return nil
    }

    override var userInfo: [NSObject: AnyObject]? {
        return nil
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    init(someCustomData: String) {
        // Compiler wants me to call super.init, but this causes
        // issues since NSNotification is a class cluster.
    }

}


If I try calling super.init or using one of the NSNotification initializers when I instantiate an instance of MyNotification, I get this error:


*** initialization method -initWithName:object:userInfo: cannot be sent to an abstract object of class MyNotification: Create a concrete instance!


Is this currently impossible to do with Swift?


Thanks!

Answered by lt_rtaylor in 10082022

Just a quick follow-up to my original post. Apple engineers at WWDC confirmed that this is currently not possible, but they are working on this internally right now. It may be resolved by the final release of iOS 9, otherwise we'll have to wait until iOS 10.

Accepted Answer

Just a quick follow-up to my original post. Apple engineers at WWDC confirmed that this is currently not possible, but they are working on this internally right now. It may be resolved by the final release of iOS 9, otherwise we'll have to wait until iOS 10.

You say "I've done this in the past with Objective-C", but that does not seem possible either. Calling [super init] results in :


*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** -[MyNotification init]: should never be used'


Do you have an example of how you've done it in objc?

Swift: Subclassing NSNotification
 
 
Q