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

时间:2017-01-19 17:39:49

标签: dictionary swift3 structure swift-playground swift2.3

我遇到了一个小问题。

假设我有结构

struct AlertNotificationObject {

    let message: String
}

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

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)

应用内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中有效。欢迎任何建议。

Unfortunately it throws me this error

1 个答案:

答案 0 :(得分:1)

在Swift 3中,Notification实际上是一个结构,更新后可以很好地使用swift,用户信息字典是[AnyHashable : Any]。您可以将结构(值类型)放入Any

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

AnyObject仅代表类,你不能在那里放置一个结构。

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