Reputation: 739
I am learning Swift and am trying to understand something regarding downcasting. NSDictionary is represented in Swift as [NSObject:AnyObject]. From what I can tell, this can be downcasted to more specific types (e.g. [Int: String]). I get that NSObject is the base class when we're talking about Objective-C, but how is it that in Swift it can be downcasted to, say, a String or Integer? It was my understanding that Swift native types aren't subclasses from NSObject.
Upvotes: 3
Views: 235
Reputation: 14824
Good question! What's actually happening is some magic in the interaction between Objective-C and Swift to make your life easier: you can downcast to, for example, [String: Int]
if your original NSDictionary
contains NSString
s and NSNumber
s. While NSString
and NSNumber
are indeed different types than String
and Int
, there is such an obvious correlation that Apple decided to do the conversion for you. In other words, it works for the same reason that this works:
let object = NSNumber(value: 4)
let swiftVersion = object as Int
Upvotes: 5