swift - Swift 3 中的 NSKeyValueChangeKey 类型转换错误

标签 swift

我一直在尝试从 2.3 迁移到 Swift 3,并且在阅读所有 SO posts 之后,其中几个显示了类似的错误但不完全相同,但我无法解决此错误。

“[NSKeyValueChangeKey : Any]”不能转换为“[String : Int]”

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {

        guard let changeKeys = change  as? [String: Int] else {
            print("changeKeys  failed")
            return
        }
}

我该如何解决这个问题?

最佳答案

在 Swift 3 中,change 参数包含一个带有预定义 NSKeyValueChangeKey 键的字典

  • indexesKey
  • kindKey
  • 新 key
  • notificationIsPriorKey
  • 旧 key

对应的值就是变化的对象。例如

if let foo = change?[.newKey] as? Int 

关于swift - Swift 3 中的 NSKeyValueChangeKey 类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42892506/

相关文章:

html - 如何在 swift 中从 html 字符串转换 NSAttributedString?

swift - 尽管控制台指示事件,但按下导航栏按钮时 UIAlertController 未显示?

swift - 对网络和本地 api 使用相同的类/模型

arrays - 将可选元组添加到数组中

macos - 从应用程序重新启动 Dock

swift - 如何在 Swift 上使用函数 NSLayoutConstraint.constraintsWithVisualFormat?

objective-c - 从 Reference 而不是 String 实例化类

swift - 如何以编程方式创建 Unwind segue

ios - 将委托(delegate)加载到 UITableView 时获取 EXC_BAD_INSTRUCTION

ios - CoreBluetooth 中心在指定服务时未发现任何外围设备