Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object (Optional Any): get elements

I’m trying to pass information with an observed notification in my app.
The standard way to do that, is to set the userinfo. However, the data I want to pass is a Set, not a dictionary.

So, I do this:

NotificationCenter.default.post(name: MY_NOTIFICATION_NAME, object:self.productIds)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The object arrives fine, but now I’m unable to get to it:

in the console I do this:

po notification.object!
▿ 2 elements
 - 0 : ZTJ
 - 1 : ZTM

However, when I try to get to one of the elements, I get this:

po notification.object![0]
error: <EXPR>:8:21: error: value of type 'Any' has no subscripts
notification.object![0]

What am I doing wrong?

>Solution :

You know that notification.object is a Set, but the compiler doesn’t because it’s declared as Any, which means it could be anything, and so it can’t find which implementation of object[0] it should use.

To read this object you need to cast it to a set.

if let mySet = notification.object as? Set<MyType> {
  // Do whatever
}

Keep in mind that the object property of Notification is designed to be used as a filter, If you pass a value when adding an observer, you’ll only get notifications that are sent with that exact same object.

The userInfo dictionary is to send related information, like your set. In this case I would send a dictionary like this:

NotificationCenter.default.post(name: MY_NOTIFICATION_NAME, object: nil, userInfo: ["products": productIds])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading