简体   繁体   中英

Reading NSNotification userInfo in Swift

(I'm new to Swift and iOS development in general).

I'm porting some Objective-C code over to Swift and I don't know how to translate this:

-(void) fooDidBar:(NSNotification *)notification
{
    Foo* foo = [[notification userInfo] objectForKey:BarKey];
    // do stuff with foo
}

So far I have this:

private func fooDidBar(notification: NSNotification) {
    var foo: Foo = notification.userInfo.objectForKey(BarKey)
}

But I get a compiler error:

/Users/me/src-me/project/FooBarViewController.swift:53:57: Value of type '[NSObject : AnyObject]?' has no member 'objectForKey'

As userInfo is declared as an NSDictionary in UIApplicationShortcutItem.h :

@property (nullable, nonatomic, copy) NSDictionary<NSString *, id <NSSecureCoding>> *userInfo;

...I thought I'd try this:

= notification.userInfo[BarKey]

but then I get this error:

/Users/me/src-me/project/FooBarViewController.swift:53:65: Type '[NSObject : AnyObject]?' has no subscript members

Your idea to use subscripts was correct, however as you can see by the presence of ? , the userInfo dictionary is Optional , meaning that it can be nil (in Objective-C, no distinction is made). Furthermore, Swift's Dictionary is not as lenient with types as NSDictionary, so you'll need to use as? to ensure the value is a Foo instance as you expect.

You can't directly subscript the optional dictionary, but if you use a ? for optional chaining , then you can access the value if the dictionary is non-nil. I would also recommend if let to access the final value if it's non-nil. (Or you might choose to use guard let with a fatalError or return in case the Foo is not present.)

if let foo = notification.userInfo?[BarKey] as? Foo {
    // foo is non-nil (type `Foo`) in here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM