ios - 在 Swift 中读取 NSNotification userInfo

标签 ios objective-c swift cocoa-touch

(我是 Swift 和 iOS 开发的新手)。

我正在将一些 Objective-C 代码移植到 Swift,但我不知道如何翻译:

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

到目前为止我有这个:

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

但是我得到一个编译器错误:

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

由于 userInfoUIApplicationShortcutItem.h 中声明为 NSDictionary:

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

...我想我会试试这个:

= notification.userInfo[BarKey]

但是我得到了这个错误:

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

最佳答案

您使用下标的想法是正确的,但是您可以从 ? 的存在看出,userInfo 字典是 Optional ,意味着它可以是 nil(在 Objective-C 中,没有区别)。此外,Swift 的 Dictionary 不像 NSDictionary 那样对类型宽松,因此您需要使用 as? 来确保该值是您期望的 Foo 实例。

你不能直接下标可选字典,但如果你使用 ? for optional chaining ,那么如果字典不为零,您就可以访问该值。我还建议 if let 访问非 nil 的最终值。 (或者您可以选择将 guard letfatalErrorreturn 一起使用,以防 Foo 不存在。)

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

关于ios - 在 Swift 中读取 NSNotification userInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35766406/

相关文章:

iphone - iOS : Get angle to geolocation from current location without map

objective-c - "Couldn’ t 在 10.10 上与辅助应用程序通信

ios - 是否有任何工作算法可以在所有 iOS 设备(有或没有 M7 芯片)上计算步数?

swift - CollectionViewCell、MapView 和自定义注释

objective-c - Transient NSPopover 燕子先点击父窗口控件

ios - Swift:声明空元组

ios - 2 带有 ADHoc 的 springBoard 中相同应用程序的图标

ios - ONLongPressGesture 作用于移动而不是长按

ios - XIB 中设置的 UIButton 操作但未触发

iphone - 完全关闭应用程序时核心数据删除问题