Typecasting in Swift

前端 未结 2 1733
渐次进展
渐次进展 2020-12-29 07:59

I am writing a library which can parse typed Ids from JSON. However, I am finding the typecasting rules a little baffling.

Example:



        
2条回答
  •  猫巷女王i
    2020-12-29 08:44

    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.

    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.

    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. But if the variable contains an instance of B, you can downcast to B, but not to C.

    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). If you are able to do that, then your code would look like:

    var json: AnyObject? = "test"
    if let string = json as? NSString {
        let a = AccountId(string: string)
    }
    

    and at that point you can use a where an instance of either AccountId or NSString is expected

提交回复
热议问题