Search code examples
dictionaryswift3structureswift-playgroundswift2

What is difference between Swift 2.3 and 3 in adding userInfo to NSNotification?


I've encountered a little problem.

Let's say that I have structure.

struct AlertNotificationObject {

    let message: String
}

I have project in Swift 2.3 where I use this structure to put into dictionary, then into userInfo: in NSNotification Observer. I couldn't get it work so in order to investigate my problem, I created some playground.

Swift 3.0 version - works as intended.

Please notice that I had to create empytClass just to get it work in Swift 3 playground.

class emptyClass{
    @objc public func testFunction(){
        print ("It should work")
    }
}

//MARK: observer //shouldnt bother us now.
let emptyClassRef = emptyClass()

NotificationCenter.default.addObserver(emptyClassRef, selector: #selector(emptyClass.testowFunction), name: NSNotification.Name(rawValue: "test0"), object: nil)

//MARK: post
let messageObject0 = AlertNotificationObject(message: "Test1")
let messageDict0 = [1: messageObject0]

let test0 = NSNotification.init(name: NSNotification.Name(rawValue: "test0"), object: nil, userInfo: messageDict0)
NotificationCenter.default.post(test0 as Notification)

In-app Swift 2.3 version - aside of obvious syntax changes, I couldn't get this to work properly - I got stuck in Notification posting.

    let messageObject0 = AlertNotificationObject(message: "test")
    let messageDict = [1: messageObject0]
    let showAlertWithBlur = NSNotification.init(name: "ShowAlertBlur", object: nil, userInfo: messageDict)
    NSNotificationCenter.defaultCenter().postNotification(showAlertWithBlur)

And I've got an error... I would like to understand what's wrong here and above all to know why it worked in Swift 3. Any suggestions, welcome.

.Unfortunately it throws me this error


Solution

  • In Swift 3, the Notification is actually a struct, updated to work nicely with swift and the user info dictionary is a [AnyHashable : Any]. You can put a struct (a value type) into Any.

    If you use the NSNotification directly (which is your only option in Swift 2), userInfo has type NSDictionary which is translated to Swift as [AnyHashable: Any] in Swift 3 and as [NSObject: AnyObject] in Swift 2.

    AnyObject represents only classes, you cannot put a struct there.

    My advice - don't use structs in Swift 2.x when interacting with Obj-C types.