[NSObject : AnyObject]?在 Xcode 6 beta 6 中没有名为“下标"的成员错误

问题描述:

当键盘显示在屏幕上时,我使用了以下几行代码来获取键盘的框架.我已注册UIKeyboardDidShowNotification 通知.

I used the below couple of code lines to get the frame of the keyboard when its shown on the screen. I've registered to UIKeyboardDidShowNotification notification.

func keyboardWasShown(notification: NSNotification) {
    var info = notification.userInfo
    var keyboardFrame: CGRect = info.objectForKey(UIKeyboardFrameEndUserInfoKey).CGRectValue()
}

这曾经在 beta 5 中工作.我下载了最新的 Xcode 6 版本,它是 beta 6,这个错误发生在第二行.

This used to work in beta 5. I downloaded the latest Xcode 6 version which is beta 6 and this error occurred at the second line.

'[NSObject : AnyObject]?'没有名为objectForKey"的成员

在谷歌搜索之后,我发现了这个解决方案.我就这样改了,

After some Googling, I came across this solution. And I changed it like so,

var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue()

但现在似乎也过时了.因为我现在收到这个错误.

But it seems that's also outdated now. Because I get this error now.

'[NSObject : AnyObject]?'没有名为下标"的成员

我无法弄清楚这个错误或如何解决它.

I can't figure out this error or how to resolve it.

正如 Xcode 6 beta 6 发行说明中提到的,大量 Foundation API 已经过审核以确保可选一致性.这些更改将 T! 替换为 T?T,具体取决于值是否可以分别为 null(或不为 null).

As mentioned in the Xcode 6 beta 6 release notes, a large number of Foundation APIs have been audited for optional conformance. These changes replace T! with either T? or T depending on whether the value can be null (or not) respectively.

notification.userInfo 现在是一个可选字典:

class NSNotification : NSObject, NSCopying, NSCoding {
    // ...
    var userInfo: [NSObject : AnyObject]? { get }
    // ...
}

所以你必须打开它.如果你知道 userInfo 不是 nil 那么您可以简单地使用强制展开":

so you have to unwrap it. If you know that userInfo is not nil then you can simply use a "forced unwrapping":

var info = notification.userInfo!

但请注意,如果 userInfonil,这将在运行时崩溃.

but note that this will crash at runtime if userInfo is nil.

否则最好使用可选赋值:

Otherwise better use an optional assignment:

if let info = notification.userInfo {
    var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
} else {
    // no userInfo dictionary present
}