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.
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 NSStrings and NSNumbers. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With