Class casting dynamically in swift

后端 未结 5 2023
慢半拍i
慢半拍i 2021-02-19 15:11

I am trying to dyanmically cast to a class in Swift. Is this possible? Here is the code I am trying to use:

let stringClass: AnyClass = NSString.self
let anyObje         


        
5条回答
  •  無奈伤痛
    2021-02-19 15:39

    The x as! Y.Type syntax only works when Y is explicitly stated.

    So, the compiler wants x as! NSString. The compiler crash is a bug, I suggest that you file a report.

    And just think about it for a second, how would that even help you? stringClass is of type AnyClass, and you're force casting an AnyObject which already conforms to AnyClass. You should cast when you have a static type in mind, because casting doesn't really make any sense otherwise.

    If you want to check, however, whether your object's class is a subclass of a particular type, you'd use:

    x is Y.Type

提交回复
热议问题