如何将NSDictionary转换为字典?

时间:2016-11-01 10:48:29

标签: swift dictionary nsdictionary objective-c-swift-bridge

我已经更新到XCode 8,现在我需要将我的代码从Swift 2转换为Swift 3。

之前,当我想将NSDictionary转换为Dictionary时,我刚写了以下内容:

let post_paramsValue = post_params as? Dictionary<String,AnyObject?>

其中post_paramsNSDictionary

但是现在使用Swift 3,我收到了这个错误:

NSDictionary is not convertible to Dictionary

为什么呢?什么改变了?

编辑1

我还尝试过以下方法:

let post_paramsValue = post_params as Dictionary<String,Any>

但是这给出了这个错误:

'NSDictionary!' is not convertible to 'Dictionary<String, Any>'; did you mean to use <code>as!</code> to force downcast?

编辑2

我还尝试过以下方法:

let post_paramsValue =  post_params as Dictionary<String,Any>

我宣布NSDictionary而不是NSDictionary!,但它不起作用;我收到了这个错误:

'NSDictionary' is not convertible to 'Dictionary<String, Any>'; did you mean to use <code>as!</code> to force downcast?

编辑3

我还尝试过以下方法:

let post_paramsValue =  post_params as Dictionary<String,Any>!

但我收到了这个错误:

'NSDictionary!' is not convertible to 'Dictionary<String, Any>!'; did you mean to use <code>as!</code> to force downcast?

3 个答案:

答案 0 :(得分:13)

    Objective-C中的
  • NSDictionary始终是非可选值。
  • AnyObject已成为Swift 3中的Any
  • 考虑前两个&#34;规则&#34; NSDictionary可以桥接到Dictionary
let post_paramsValue = post_params as Dictionary<String,Any>

如果来源NSDictionary是可选的,您可以使用as Dictionary<String,Any>?as? Dictionary<String,Any>as! Dictionary<String,Any>as Dictionary<String,Any>!,具体取决于{{1}的实际类型}}

答案 1 :(得分:1)

您只需要在objc中正确声明NSDictionary

例如:NSDictionary<NSString *, NSString*>在快捷界面中自动翻译为[String: String]

答案 2 :(得分:0)

对于那些NSDictionary有问题的人,只需使用此扩展程序:

Swift 3.0

extension NSDictionary {
    var swiftDictionary: Dictionary<String, Any> {
        var swiftDictionary = Dictionary<String, Any>()

        for key : Any in self.allKeys {
            let stringKey = key as! String
            if let keyValue = self.value(forKey: stringKey){
                swiftDictionary[stringKey] = keyValue
            }
        }

        return swiftDictionary
    }
}