Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert NSDictionary to Dictionary?

I have already updated to XCode 8 and now I need to convert my code from Swift 2 to Swift 3.

Before, when I want to convert NSDictionary to Dictionary, I just wrote the following:

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

where post_params is NSDictionary.

But now with Swift 3, I am receiving this error:

NSDictionary is not convertible to Dictionary

Why? What's changed?


Edit 1

I've also tried the following:

let post_paramsValue = post_params as Dictionary<String,Any>

But that 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've also tried the following:

let post_paramsValue =  post_params as Dictionary<String,Any>

Where I declare NSDictionary instead of NSDictionary!, but it doesn't 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've also tried the following:

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

But I received this error:

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

like image 629
david Avatar asked Nov 01 '16 10:11

david


People also ask

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary creates static dictionaries, and NSMutableDictionary creates dynamic dictionaries.

What is NSDictionary in Swift?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.


1 Answers

  • NSDictionary in Objective-C has always non-optional values.
  • AnyObject has become Any in Swift 3.
  • Considering the first two "rules" NSDictionary can be bridge cast to Dictionary

let post_paramsValue = post_params as Dictionary<String,Any>

If the source NSDictionary is an optional you might use as Dictionary<String,Any>? or as? Dictionary<String,Any> or as! Dictionary<String,Any> or as Dictionary<String,Any>! depending on the actual type of the NSDictionary

like image 142
vadian Avatar answered Sep 18 '22 11:09

vadian