Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downcasting NSObject in Swift

Tags:

ios

swift

cocoa

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.

like image 231
Drew Avatar asked Dec 01 '25 04:12

Drew


1 Answers

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
like image 58
andyvn22 Avatar answered Dec 02 '25 20:12

andyvn22