12

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"

JackWhiteIII
  • 1,388
  • 2
  • 11
  • 25
msalafia
  • 2,703
  • 5
  • 23
  • 34
  • 1
    It seems that it doesn't know that userInfo is an NSDictionary. Have you tried var info = `notification.userInfo as NSDictionary` ? with your first code – Paulw11 Jul 08 '14 at 09:23
  • No, i've tryed it right now and it works perfectly! Thank you! But why it doesn't recognize userInfo like NSDictionary? – msalafia Jul 08 '14 at 09:26

1 Answers1

18

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382