Swift 2.3 和 3 将 userInfo 添加到 NSNotification 有什么区别?

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

我遇到了一个小问题。

假设我有结构

struct AlertNotificationObject {

    let message: String
}

我在 Swift 2.3 中有一个项目,我使用这个 结构 放入 字典 ,然后放入 [=31] =]userInfo: 在 NSNotification 观察者中。我无法让它工作,所以为了调查我的问题,我创建了一些游乐场。

Swift 3.0 版本 - 按预期工作。

请注意,我必须创建 empytClass 才能让它在 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)

应用程序内 Swift 2.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 中,Notification 实际上是一个结构,更新后可以很好地与 swift 一起使用,用户信息字典是 [AnyHashable : Any]。您可以将结构(值类型)放入 Any.

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

AnyObject 只代表 类,你不能把结构放在那里。

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