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

1

25

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.

Eventide answered 19/8, 2014 at 10:40 Comment(0)
W
41

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
}
Worn answered 19/8, 2014 at 11:3 Comment(4)
Thanks, Martin. It worked. I went with the unwarpping. Is there any downsides to it?Eventide
@Isuru: See updated answer. If you know that userInfo is not nil then you can just unwrap. Otherwise use the optional assignment.Worn
I get an error with Swift 1.2: Cannot subscript a value of type 'AnyObject' with an index of type StringCarpous
@VanDuTran: That is strange. I have double-checked the code with Swift 1.2 and with Swift 2 and it compiles without problems for me.Worn

© 2022 - 2024 — McMap. All rights reserved.