【问题标题】:Cast from '[NSObject : AnyObject]?' to unrelated type 'NSDictionary' always fails从 '[NSObject : AnyObject]?' 转换到不相关的类型“NSDictionary”总是失败
【发布时间】:2015-11-03 13:02:57
【问题描述】:

这条线let userInfo = notification.userInfo as! NSDictionary我收到警告:Cast from '[NSObject : AnyObject]?' to unrelated type 'NSDictionary' always fails

我尝试使用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 Yosemite

这是我的代码:

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()
    }


}

【问题讨论】:

  • 只使用 Swift 原生字典
  • 我尝试使用let userInfo = notification.userInfo as! Dictionary<NSObject: AnyObject>,但它是错误的,我得到一个错误。
  • 为什么要进行类型转换?

标签: swift nsdictionary


【解决方案1】:

NSNotification 的 userInfo 属性已经被定义为一个(n 可选)字典。

所以你根本不需要投射它,只需打开它。

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

您的所有其他代码都应该按原样工作。

【讨论】:

  • 展开是作者需要从中得到的主要内容;您不能将[NSObject : AnyObject]? 转换为NSDictionary,因为前者是可选的,而后者不是。您可以转换为NSDictionary?,或者您可以打开并转换为NSDictionary。但是,正如您所说,实际上您只需要打开包装,然后就可以在本地使用它,而无需桥接回 Objective-C 类型。
  • 我明白了。你的风格各不相同。
【解决方案2】:

您正试图强制将一个可选项强制转换为 NSDictionary。试试:

let userInfo = notification.userInfo! as NSDictionary

这对我有用。

【讨论】:

  • 我试过了。也没关系。我认为 Tristan Burnside 的回答更合理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多