Dictionary doesn't recognize key type
dictionary, ios, swift, xcode
Solution
As of Xcode 6 Beta 3, `NSDictionary*` is now imported from Objective-C APIs as `[NSObject : AnyObject]` (this change is documented in the release notes).
So you can access the dictionary value with `info[UIKeyboardFrameBeginUserInfoKey]`. This gives an `AnyObject` which you have to cast to `NSValue`, so that `CGRectValue()` can be applied:
var info = notification.userInfo
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as NSValue).CGRectValue().size
The error message
'String' is not a subtype of 'DictionaryIndex'
is quite misleading, the problem with your second attempt is only the missing cast.
Update for Xcode 6.3: `notification.userInfo` is an optional dictionary now and must be unwrapped, e.g. with optional binding. Also the forced cast operator `as` has been renamed to `as!`:
if let info = notification.userInfo {
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue().size
} else {
// no user info
}
We can forcefully unwrap the dictionary value because it is documented to be a `NSValue` of a `CGRect`.
Problem
With the beta 3 of Xcode the following piece of code doesn't work anymore: ``` func keyboardWasShown (notification: NSNotification) { var info = notification.userInfo keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size } ``` at the instruction: ``` keyboardSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey).CGRectValue().size ``` XCode return the error [NSObject : AnyObject] does not have a member named objectForKey. So i changed the code like this: ``` func keyboardWasShown (notification: NSNotification) { var info = notification.userInfo keyboardSize = info[UIKeyboardFrameBeginUserInfoKey].CGRectValue().size } ``` but XCode returns the error "String is not a subtype f DictionaryIndex"