我有以下代码:
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。现在我想从这本词典中获取一些元素。但似乎并非我想要使用的所有项目都继承自AnyObject
。 UIViewAnimationCurve
为enum
,CGRect
为struct
。
我正在从Objective-C翻译此代码,其中使用以下语法:
[[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
现在我想知道如何在不使用(不安全)指针的情况下从字典中获取这些元素。
答案 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