Subclass NSNotification with Generics in Swift 2.1

Unable to subclass NSNotification using Generic payload object. Getting a run-time error or a compilation error (see comments in the code below). Is this possible with Swift 2.1? Any ideas appreciated. Thanks!

Runtime error because NSNotification is an abstract class (class cluster).
A compilation error because the designated initializer must be used.

 public class Notification<T: Any>: NSNotification { private var _name: String private var _object: AnyObject? private var _payload: T? public override var name: String { return _name } public override var object: AnyObject? { return _object } public var payload: T? { return _payload } /// Always nil. Use payload public override var userInfo: [NSObject : AnyObject]? { return nil } /// Change to false to "swap" implementation #if true init(name: String, object: AnyObject? = nil, payload: T? = nil) { _name = name _object = object _payload = payload /* Runtime error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** initialization method -initWithName:object:userInfo: cannot be sent to an abstract object of class _TtGC14__lldb_expr_1612NotificationSS_: Create a concrete instance!' */ super.init(name: name, object: object, userInfo: nil) } #else convenience init(name: String, object: AnyObject? = nil, payload: T? = nil) { self.init() _name = name _object = object _payload = payload } init() { /// compiler error: /// must call a designated initializer of the superclass /// But using designated initializer cause runtime error listed above. super.init() } #endif } let n = Notification<String>(name: "xyz", payload: "Hello") 
+6
source share
1 answer

From the documentation , my focus:

You can subclass NSNotification contain information in addition to the name, object, and notification dictionary. These additional data must be agreed between observers and observers.

NSNotification - a cluster of classes without instance variables. Therefore, you must subclass NSNotification and override the primitive methods name , object and userInfo . You can select any initializer assigned to you, but make sure that your initializer does not call [super init] . NSNotification not intended to be created directly, and the init method throws an exception.

Swift does not currently have an NSNotification subclass, since Swift does not have the concept of "uninitializable classes" and requires all subclasses to call their superclass init (which is incorrect in this case).

You will need to write a subclass in Objective-C and move it to your Swift code.

Unfortunately, even though you can declare your Objective-C class public, this information is lost in the bridge process. From the docs :

In addition to these Foundation collection classes, Objective-C light generics are ignored by Swift. Any other types that use lightweight generics are imported into Swift, as if they were not parameterized.

: (

+7
source

All Articles