为什么我不能在通知中将数组转换为 AnyObject?
Why can't I cast an array to AnyObject in a notification?
我有一个 RequestError 数组,我想将其传递给通知 userInfo 对象。
let errors: [RequestError]
let errorDictionary = ["errors": errors]
NSNotificationCenter.defaultCenter().notificationCenter.postNotificationName(UserSaveFailKey, object: self, userInfo: errorDictionary)
为什么我得到
Cannot convert value of type '[String : [RequestError]]' to expected
argument type '[NSObject : AnyObject]?'
如果 RequestError
是 enum
或 struct
,则它不是引用类型,它们的数组将不符合 AnyObject
,因为它无法转换为 NSArray
.
您可以通过创建包装器来解决此问题 class:
class RequestErrorsWrapper {
let errors: [RequestError]
init(errors: [RequestError]) {
self.errors = errors
}
}
let errorDictionary = ["errors": RequestErrorsWrapper(errors: errors)]
NSNotificationCenter.defaultCenter().postNotificationName(UserSaveFailKey, object: self, userInfo: errorDictionary)
然后在接收端,你会像这样解压错误:
if let wrapper = notification.userInfo?["errors"] as? RequestErrorsWrapper {
let errors = wrapper.errors
// use errors
}
我有一个 RequestError 数组,我想将其传递给通知 userInfo 对象。
let errors: [RequestError]
let errorDictionary = ["errors": errors]
NSNotificationCenter.defaultCenter().notificationCenter.postNotificationName(UserSaveFailKey, object: self, userInfo: errorDictionary)
为什么我得到
Cannot convert value of type '[String : [RequestError]]' to expected argument type '[NSObject : AnyObject]?'
如果 RequestError
是 enum
或 struct
,则它不是引用类型,它们的数组将不符合 AnyObject
,因为它无法转换为 NSArray
.
您可以通过创建包装器来解决此问题 class:
class RequestErrorsWrapper {
let errors: [RequestError]
init(errors: [RequestError]) {
self.errors = errors
}
}
let errorDictionary = ["errors": RequestErrorsWrapper(errors: errors)]
NSNotificationCenter.defaultCenter().postNotificationName(UserSaveFailKey, object: self, userInfo: errorDictionary)
然后在接收端,你会像这样解压错误:
if let wrapper = notification.userInfo?["errors"] as? RequestErrorsWrapper {
let errors = wrapper.errors
// use errors
}