我遇到了一个小问题。
假设我有结构。
struct AlertNotificationObject {
let message: String
}我在SWIFT2.3中有一个项目,我使用这个结构将其放入字典,然后放入userInfo: in NSNotification观察者中。我无法使它工作,所以为了调查我的问题,我建立了一些操场。
SWIFT3.0版本的-按预期工作。
请注意,为了让它在Swift 3操场上工作,我不得不创建empytClass。
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 SWIFT2.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中工作。欢迎任何建议。
。

发布于 2017-01-19 18:07:33
在Swift 3中,Notification实际上是一个结构,可以很好地与[AnyHashable : Any]一起工作,并且用户信息字典是一个[AnyHashable : Any]。您可以将一个结构(值类型)放入Any中。
如果您直接使用NSNotification (这是Swift 2中唯一的选项),userInfo的类型是NSDictionary,它在Swift 3中转换为[AnyHashable: Any],在Swift 2中转换为[NSObject: AnyObject]。
AnyObject只表示类,您不能在那里放置一个结构。
我的建议是,在与Obj类型交互时,不要在Swift 2.x中使用structs。
https://stackoverflow.com/questions/41748264
复制相似问题