实际上,NSString.class甚至不起作用!您必须使用NSString.self.let s = NSString.selfvar str = s()str = "asdf"类似地,我尝试了一个快速的课程... class MyClass {}let MyClassRef = MyClass.self// ERROR :(let my_obj = MyClassRef()嗯...错误提示: 操场执行失败:错误::16:1:错误:用元类型值构造类类型为'X'的对象需要一个'@required'初始化程序 Y().me() ^ <REPL>:3:7: note: selected implicit initializer with type '()' class X { ^我花了一段时间才弄清楚这意味着什么……事实证明,它希望班级有一个@required init() class X { func me() { println("asdf") } required init () { }}let Y = X.self// prints "asdf"Y().me()有些文档将其称为.Type,但是MyClass.Type在操场上给了我一个错误.I am trying to dynamically create a class instance based type using generics, however I am encountering difficulty with class introspection.Here are the questions:Is there a Swift-equivalent to Obj-C's self.class?Is there a way to instantiate a class using the AnyClass result from NSClassFromString?Is there a way to get AnyClass or otherwise type information strictly from a generic parameter T? (Similar to C#'s typeof(T) syntax) 解决方案 Well, for one, the Swift equivalent of [NSString class] is .self (see Metatype docs, though they're pretty thin).In fact, NSString.class doesn't even work! You have to use NSString.self.let s = NSString.selfvar str = s()str = "asdf"Similarly, with a swift class I tried...class MyClass {}let MyClassRef = MyClass.self// ERROR :(let my_obj = MyClassRef()Hmm… the error says: Playground execution failed: error: :16:1: error: constructing an object of class type 'X' with a metatype value requires an '@required' initializer Y().me() ^ <REPL>:3:7: note: selected implicit initializer with type '()' class X { ^It took me a while to figure out what this means… turns out it wants the class to have a @required init()class X { func me() { println("asdf") } required init () { }}let Y = X.self// prints "asdf"Y().me()Some of the docs refer to this as .Type, but MyClass.Type gives me an error in the playground. 这篇关于Swift类自省&仿制药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-29 05:58