Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 使用NSClassFromString(“MyUIViewController”)的结果进行动态转换_Swift - Fatal编程技术网

Swift 使用NSClassFromString(“MyUIViewController”)的结果进行动态转换

Swift 使用NSClassFromString(“MyUIViewController”)的结果进行动态转换,swift,Swift,我发现下面的代码不起作用,但我不明白为什么 假设我有一个保存在字符串中的类名。我想将视图控制器强制转换为该字符串所引用的类 let controller = self.navigationController as! NSClassFromString("MyUIViewController") 斯威夫特似乎不明白这一点-我得到这个错误: Undeclared use of NSClassFromString. 或错误: Consecutive statements must be sepa

我发现下面的代码不起作用,但我不明白为什么

假设我有一个保存在字符串中的类名。我想将视图控制器强制转换为该字符串所引用的类

let controller = self.navigationController as! NSClassFromString("MyUIViewController")
斯威夫特似乎不明白这一点-我得到这个错误:

Undeclared use of NSClassFromString.
或错误:

Consecutive statements must be separated by `,`
有人能解释为什么会这样吗?我不能用as来施法?基于某个变量的类型


谢谢

否,您不能强制转换为运行时类型的对象。必须强制转换为编译时类型。这就是为什么我们将x写为Int,而不是将x写为Int.self的原因:Int是一个类型,而Int.self是一个在运行时表示该类型的对象

从StringMyUIViewController强制转换到NSClassFromStringMyUIViewController意味着什么?现在有了一个变量controller,它的值是编译器不知道的某种类型,所以编译器不能让您对controller做任何事情。您不能调用方法或访问它的属性,因为编译器不知道它有什么方法或属性。不能将其作为参数传递给函数,因为编译器不知道该参数的类型是否正确


如果您编辑您的问题来解释您想对控制器执行什么操作,您想调用什么方法,或者您想访问什么属性,或者您想将其传递给什么函数,那么我将修改我的答案以实现您的目标。

在Swift中不是那么简单,您可能需要检查以下内容: