Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between NSDictionary vs Dictionary in Swift?

Tags:

I'm learning Swift, and I can see Dictionary in it.
But there are lots of examples that are using NSDictionary with Swift.
What's the difference between these two?
I want to use an array with index in Swift like an array in PHP.
Which one is better to use?

like image 901
TomSawyer Avatar asked Aug 28 '14 17:08

TomSawyer


People also ask

What is NSDictionary in Swift?

In Swift, the NSDictionary class conforms to the DictionaryLiteralConvertible protocol, which allows it to be initialized with dictionary literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).

How do you append NSMutableDictionary?

Use NSMutableDictionary addEntriesFromDictionary to add the two dictionaries to a new mutable dictionary. You can then create an NSDictionary from the mutable one, but it's not usually necessary to have a dictionary non-mutable. Show activity on this post.


2 Answers

Dictionary is a native Swift struct. NSDictionary is a Cocoa class. They are bridged to one another (within the usual limits), as the docs explain very clearly and fully.

It's exactly parallel to Array and NSArray.

like image 156
matt Avatar answered Oct 05 '22 23:10

matt


In practice and with regard to Swift's strong type concept the significant difference is

  • NSDictionary is generally type unspecified
  • Dictionary is supposed to have a specific type.

Hence native Dictionary is preferable.

like image 34
vadian Avatar answered Oct 05 '22 22:10

vadian