How can I convert an NSDictionary to a dictionary?

I have already upgraded to Xcode 8 and now I need to convert the code from Swift 2 to Swift 3.

Previously, when I wanted to convert NSDictionaryto Dictionary, I just wrote the following:

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

where post_paramsis it NSDictionary.

But now with Swift 3, I get this error:

NSDictionary is not convertible to Dictionary

What for? What changed?


Edit 1

I also tried the following:

let post_paramsValue = post_params as Dictionary<String,Any>

But this gives this error:

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


Edit 2

I also tried the following:

let post_paramsValue =  post_params as Dictionary<String,Any>

Where I declare NSDictionaryinstead NSDictionary!, but this does not work; I got this error:

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


Edit 3

I also tried the following:

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

But I got this error:

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

+5
source share
2
  • NSDictionary Objective-C .
  • AnyObject Any Swift 3.
  • "" 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>! NSDictionary

+12

, 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
    }
}
+1

Source: https://habr.com/ru/post/1659503/


All Articles