[NSObject : AnyObject]?' does not have a member named 'subscript' error in Xcode 6 beta 6

╄→尐↘猪︶ㄣ 提交于 2019-11-26 08:28:48

问题


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()
}

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]?\' does not have a member named \'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]?\' does not have a member named \'subscript\'

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


回答1:


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 is now an optional dictionary:

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

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!

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
}


来源:https://stackoverflow.com/questions/25381338/nsobject-anyobject-does-not-have-a-member-named-subscript-error-in-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!