Types-the String type’s interpolation and Swift-designed APIs and the Use a Swift String type instead and gain the benefits of both This means that anywhere you use an NSString object, you can Swift automatically bridges between the String type and the NSStringĬlass. Swift's String class is automatically bridged to NSString and vice versa. Is there something magical about NSString which does not crossover to Swift-only classes? If you are able to do that, then your code would look like: var json: AnyObject? = "test"Īnd at that point you can use a where an instance of either AccountId or NSString is expected In your case, rather than downcasting you should specialize a constructor accepting NSString, but I suspect that in this specific case of NSString it cannot be done (there's no NSString designated initializer accepting a string as argument). But if the variable contains an instance of B, you can downcast to B, but not to C. Note that polymorphism allows you do to upcast and downcast with variables - which means, if you have an instance of C stored in a variable of type A, you can cast that variable to B and C, because it actually contains an instance of C. The reason is that C might add properties which are not available in B, so the compiler or the runtime wouldn't know how to initialize the additional data, not to mention that it must also be allocated. As a general rule, if you have a hierarchy of classes A -> B -> C (C inherits from B, which in turn inherits from A), and you have an instance of B, you can upcast to A, but you cannot downcast to C.
0 Comments
Leave a Reply. |