2015-11-03 62 views
4

此行let userInfo = notification.userInfo as! NSDictionary我得到一个警告:Cast from '[NSObject : AnyObject]?' to unrelated type 'NSDictionary' always fails从'[NSObject:AnyObject]中投射?'无关型“的NSDictionary”总是失败

我尝试使用let userInfo = notification.userInfo as! Dictionary<NSObject: AnyObject>取代let userInfo = notification.userInfo as! NSDictionary。但是我收到一个错误:Expected '>' to complete generic argument list。如何解决警告。

的Xcode 7.1 OS X约塞米蒂

这是我的代码:

func keyboardWillShow(notification: NSNotification) { 

    let userInfo = notification.userInfo as! NSDictionary //warning 

    let keyboardBounds = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() 
    let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue 
    let keyboardBoundsRect = self.view.convertRect(keyboardBounds, toView: nil) 

    let keyboardInputViewFrame = self.finishView!.frame 

    let deltaY = keyboardBoundsRect.size.height 

    let animations: (()->Void) = { 

     self.finishView?.transform = CGAffineTransformMakeTranslation(0, -deltaY) 
    } 

    if duration > 0 { 



    } else { 

     animations() 
    } 


} 
+0

只使用Swift原生字典 –

+0

我尝试使用'let userInfo = notification.userInfo as! Dictionary '但它是错误的,我得到一个错误。 – rose

+0

为什么要输入铸件? – vadian

回答

4

NSNotification的USERINFO财产已经被定义为(N可选)字典。

所以,你根本不需要施放它,只需解开它即可。

func keyboardWillShow(notification: NSNotification) { 
    if let userInfo = notification.userInfo { 
     ... 
    } 
} 

所有其余的代码应该按原样工作。

+0

解开包装是作者需要从中取出的主要东西;你不能将'[NSObject:AnyObject]?'转换为'NSDictionary',因为前者是可选的,而后者不是。你可以转换成'NSDictionary?',或者你可以解开并转换成'NSDictionary'。但是,正如你所说的,在实践中你只需要解包,然后你就可以直接使用它,而不需要回到Objective-C类型。 – Tommy

+0

我明白了。这是你的不同种类。 – rose

+0

我已经学会了。 – rose

3

您试图强制将可选属性强制转换为NSDictionary。试试:

let userInfo = notification.userInfo! as NSDictionary 

这对我有效。

+0

我试过了。这也没关系。我认为特里斯坦伯恩赛德的答案更合理。 – rose

相关问题