Dan
Dan

Reputation: 3103

Why does Swift have both NSDictionary and Dictionary classes?

I'm new here so please help me figure this out. I wonder why does Swift have both NSDictionary and Dictionary classes? My question applies also to the other standard classes like String/NSString, Array/NSArray etc. I'm asking this because i have problem in my code, having to do a lot of casts. For example, i found the method to load a plist file into a dictionary only in NSDictionary contentsOfFile and not in the native Dictionary class, the latter being the 'advertised' way to go with Swift.

Is this an implementation problem (Swift being new and all) or are there more, deeper, reasons for having the old Objective-C classes? What are the differences?

Upvotes: 2

Views: 584

Answers (2)

Rein rPavi
Rein rPavi

Reputation: 3396

In order to simplify your question lets take an example of NSString

NSString is class for a long time in iOS development, it is the predecessor of String

String is the new Swift specific string class where as NSString is the older objective C version and there is a way to convert or bridge between the two,

As per Apple “The entire NSString API is available to call on any String value you create”

now why you want to do this because String class does’t necessarily have all the methods that is on NSString at the moment, so if you want to use method of NSString you can convert a String to NSString and take advantage of those methods

for example

// Double conversion
var strCon = Double(("3.14" as NSString).doubleValue)

// Contains String
var stack = "Stack overflow"
(stack as NSString).containsString("Stack")

// Substring
var overflow = (stack as NSString).substringToIndex(8)

In short if you are trying to do something and there doesn’t seem to be method available on String I recommend to take a look at NSString as there are tons of methods there and chances are it will help you out

same is the case with NSDictionary, NSArray and so on… I hope it helps

Upvotes: 2

Kirsteins
Kirsteins

Reputation: 27345

Both types are there in order to use Objective-C code in swift. Swift array and dictionary are generic type and can hold non-class instances (enum, struct), while NSArray/NSDictonary can only hold NSObject.

Upvotes: 2

Related Questions