0

I have the following code:

    let userInfo = notification.userInfo

    let animationCurve = userInfo?[UIKeyboardAnimationCurveUserInfoKey] as UIViewAnimationCurve
    let animationDuration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as NSTimeInterval
    let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as CGRect

userInfo is a [NSObject: AnyObject]? dictionary and the UIKeyboardAnimationCurveUserInfoKey keys are all NSString!s. Now I want to get some elements from this dictionary. But it seems not all items I want to use inherit from AnyObject. UIViewAnimationCurve is an enum and CGRect is a struct.

I am translating this code from Objective-C, where the following syntax is used:

[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];

Now I want to know how I can get these elements from the dictionary without using (unsafe) pointers.

vrwim
  • 13,020
  • 13
  • 63
  • 118
  • See http://stackoverflow.com/a/25381771/1187415 for the UIKeyboardFrameEndUserInfoKey. Similar code should work for UIKeyboardAnimationCurveUserInfoKey. – Martin R Mar 02 '15 at 10:23
  • That works for the CGRect, but not for the `UIViewAnimationCurve`, as this is an enum. I guess I'll cast it to an `Int` and then use its raw value to initialize it, I guess. – vrwim Mar 02 '15 at 10:38

1 Answers1

2

The value of UIKeyboardFrameEndUserInfoKey is a NSValue representing a CGRect:

if let tmp = userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
    let keyboardFrame = tmp.CGRectValue()
}

The value of UIKeyboardAnimationCurveUserInfoKey is a NSNumber representing the integer value of the enumeration:

if let tmp = userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
    let animationCurve = UIViewAnimationCurve(rawValue: tmp.integerValue)!
}

This can be combined into single expressions, using the nil-coalescing operator ?? to provide default values:

let keyboardFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectZero
let animationCurve = UIViewAnimationCurve(rawValue:
        (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.integerValue ?? 0
    ) ?? .Linear
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382