Dictionary Swift 2.3和3在向NSNotification添加用户信息方面有什么区别?

Dictionary Swift 2.3和3在向NSNotification添加用户信息方面有什么区别?,dictionary,swift3,structure,swift-playground,swift2.3,Dictionary,Swift3,Structure,Swift Playground,Swift2.3,我遇到了一个小问题 假设我有结构 struct AlertNotificationObject { let message: String } 我在Swift 2.3中有一个项目,我使用这个结构将其放入字典中,然后放入NSNotification Observer中的userInfo:。我无法让它工作,所以为了调查我的问题,我创建了一些游乐场 class emptyClass{ @objc public func testFunction(){ print (

我遇到了一个小问题

假设我有结构

struct AlertNotificationObject {

    let message: String
}
我在Swift 2.3中有一个项目,我使用这个结构将其放入字典中,然后放入NSNotification Observer中的userInfo:。我无法让它工作,所以为了调查我的问题,我创建了一些游乐场

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)
Swift 3.0版-按预期工作

请注意,我必须创建empytClass才能在Swift 3游乐场中运行

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)
在appswift2.3版本中-除了明显的语法更改之外,我无法使其正常工作-我被困在通知发布中

    let messageObject0 = AlertNotificationObject(message: "test")
    let messageDict = [1: messageObject0]
    let showAlertWithBlur = NSNotification.init(name: "ShowAlertBlur", object: nil, userInfo: messageDict)
    NSNotificationCenter.defaultCenter().postNotification(showAlertWithBlur)
我有一个错误。。。我想了解这里出了什么问题,最重要的是想知道为什么它在Swift 3中起作用。欢迎提出任何建议


.

在Swift 3中,
通知实际上是一个结构,已更新以与Swift配合使用,用户信息字典是一个
[AnyHashable:Any]
。您可以将结构(值类型)放入
任何

如果您直接使用
NSNotification
(这是您在Swift 2中的唯一选项),
userInfo
的类型为
NSDictionary
,在Swift 3中翻译为
[AnyHashable:Any]
,在Swift 2中翻译为
[NSObject:AnyObject]

AnyObject
只表示类,不能在其中放置结构

我的建议-在与Obj-C类型交互时,不要在Swift 2.x中使用结构