如何将具有类名称的字符串转换为类类型本身? [英] How to convert a string with the name of a class to the class type itself?
问题描述
let objectType:NSObject.Type = Object.self
let str = String(描述:objectType)
<但是,我没有成功地将 str
转换为 NSObject.Type
类型的变量来使用它在一个通用的方法中。
我怎么能做到这一点?
您可以从 string
返回类,但在获取类名时需要使用项目的 module 名称。如果您没有使用模块名称,那么它将返回 nil
,因为您之前引用的类名称未由模块名称完全限定。您应该更改类名称字符串以表示您的类的完全限定名称:
let myClassString = String(MyModule.MyViewController。 self)
print(myClassString)
let myClass = NSClassFromString(MyModule.\(myClassString))as! MyViewController.Type
print(myClass)
In order to store a class name in a log file I converted the description of a class type to a string:
let objectType: NSObject.Type = Object.self
let str = String(describing: objectType)
However, I do not succeed in back conversion of str
to a variable of type NSObject.Type
to use it in a generic method.
How could I do this?
You can get your class back from string
, but you need to use your project's module name while getting class name. If you don't use your module name then it will return nil
because the class name you have referenced earlier is not fully qualified by the module name. You should change the class name string to represent the fully qualified name of your class:
let myClassString = String(MyModule.MyViewController.self)
print(myClassString)
let myClass = NSClassFromString("MyModule.\(myClassString)") as! MyViewController.Type
print(myClass)
这篇关于如何将具有类名称的字符串转换为类类型本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!