Swift 使用类型输入变量进行类型转换

Swift 使用类型输入变量进行类型转换,swift,swift3,casting,Swift,Swift3,Casting,是否可以将对象强制转换为存储在成员变量中的类型 我试过这个: let targetClass = type(of: MyTargetClass) ... if anyObject is targetClass { // ERROR: use of undeclared type 'targetClass' let test = anyObject as! targetClass // ERROR: use of undeclared type 'targetClass' } 但是它不起作用,

是否可以将对象强制转换为存储在成员变量中的类型

我试过这个:

let targetClass = type(of: MyTargetClass)
...

if anyObject is targetClass { // ERROR: use of undeclared type 'targetClass'
let test = anyObject as! targetClass // ERROR: use of undeclared type 'targetClass'
}

但是它不起作用,因为它说“使用未声明的类型‘targetClass’”

不。类型转换是编译时的事情。它让编译器知道哪些方法可用以及如何进行链接

您可以使用在运行时收集有关对象的信息,但看起来动态调用方法仍然只能在从
NSObject
派生的类上完成