Search code examples
objective-cswiftdictionarycastingnsdictionary

What is the difference between these two options for converting Swift Dictionary to NSMutableDictionary?


In my project I have a dictionary of type [String: AnyObject] and am converting it to NSMutableDictionary to be compatible with some Objective C code in the project.

I started using the below conversion option (which I've seen as an accepted answer in many stack overflow posts):

dictionary as? NSMutableDictionary

This works in most cases, but in some instances the result was nil which indicates the dictionary could not be converted to NSMutableDictionary. However, with the exact same values in the dictionary the below conversion successfully results in an NSMutableDictionary:

NSMutableDictionary(dictionary: dictionary)

Why would the first option result in nil when the second one is able to convert without any issues?

You can see here How do I convert swift Dictionary to NSDictionary that the first option is the accepted answer, but it does not seem to work in all cases. The second option is also mentioned but does not have as many people agreeing that it is the correct answer.


Solution

  • This works in most cases

    No, this works not at all.

    Unlike immutable NSDictionary Swift Dictionary and NSMutableDictionary are not related.

    You can bridge cast (as without ?) [String:String] to NSDictionary but you cannot bridge cast nor conditionally downcast (as?) it to NSMutableDictionary.

    The second syntax works because a new instance of NSMutableDictionary is created. The Swift dictionary parameter is implicitly bridged to NSDictionary


    The same behavior is also true for Swift Array and Foundation NSMutableArray