简体   繁体   English

在Swift中读取NSNotification userInfo

[英]Reading NSNotification userInfo in Swift

(I'm new to Swift and iOS development in general). (一般来说,我是Swift和iOS开发的新手)。

I'm porting some Objective-C code over to Swift and I don't know how to translate this: 我正在将一些Objective-C代码移植到Swift,但我不知道该如何翻译:

-(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]?' /Users/me/src-me/project/FooBarViewController.swift:53:57:类型'[NSObject:AnyObject]的值?' has no member 'objectForKey' 没有成员'objectForKey'

As userInfo is declared as an NSDictionary in UIApplicationShortcutItem.h : 由于userInfoUIApplicationShortcutItem.h被声明为NSDictionary

@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]?' /Users/me/src-me/project/FooBarViewController.swift:53:65:输入'[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). userInfo字典是Optional ,意味着它可以为nil(在Objective-C中,没有区别)。 Furthermore, Swift's Dictionary is not as lenient with types as NSDictionary, so you'll need to use as? 此外,Swift的Dictionary在类型上不如NSDictionary宽大,因此您需要使用as? to ensure the value is a Foo instance as you expect. 确保该值是您期望的Foo实例。

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. 对于可选链接 ,如果字典为非nil,则可以访问该值。 I would also recommend if let to access the final value if it's non-nil. 我还建议if let访问非零的最终值。 (Or you might choose to use guard let with a fatalError or return in case the Foo is not present.) (或者您可以选择使用带有fatalError guard let fatalError或者在不存在Foo的情况下return 。)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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