Home > Blockchain >  Object (Optional Any): get elements
Object (Optional Any): get elements

Time:11-19

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)

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?

CodePudding user response:

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])

CodePudding user response:

The notification has an object type of Any?.

When you're poing it in the console, you're asking it to print its description, which Any can do.

When you're asking it to subscript, Any can't do that, because subscripting is not defined on that type. You need to cast it to the expected type:

po (notification.object as? [String])?[0]

In general, it's best to nail down the type of any Any as soon as you can. Think of Any as a box used to send things through the post. The first thing you do is open it and find out what's inside.

  • Related