从[NSString:AnyObject]获取对象为UIViewAnimationCurve?

时间:2015-03-02 10:14:41

标签: ios objective-c swift dictionary

我有以下代码:

    let userInfo = notification.userInfo

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

userInfo[NSObject: AnyObject]?词典,UIKeyboardAnimationCurveUserInfoKey个键都是NSString! s。现在我想从这本词典中获取一些元素。但似乎并非我想要使用的所有项目都继承自AnyObjectUIViewAnimationCurveenumCGRectstruct

我正在从Objective-C翻译此代码,其中使用以下语法:

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

现在我想知道如何在不使用(不安全)指针的情况下从字典中获取这些元素。

1 个答案:

答案 0 :(得分:2)

UIKeyboardFrameEndUserInfoKey的值是NSValue代表的值 CGRect

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

UIKeyboardAnimationCurveUserInfoKey的值是NSNumber 表示枚举的整数值:

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

这可以使用nil-coalescing组合成单个表达式 operator ??提供默认值:

let keyboardFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() ?? CGRectZero
let animationCurve = UIViewAnimationCurve(rawValue:
        (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.integerValue ?? 0
    ) ?? .Linear