简体   繁体   English

如何在泛型类中使用类类型

[英]How to use a class type in a generic class

From a log file I obtain a string that contains the name a class, eg "Child" that may be defined as: 从日志文件中,我获得一个字符串,其中包含一个类的名称,例如“ Child”,可以定义为:

class Child: Object, MyProtocol {
// ...
}

I want to use this class in the following generic class: 我想在以下通用类中使用此类:

open class MyClass<T: Object> where T:MyProtocol {
    //…

    open class func doSomething() {
    //…
    }

}

I already asked a question here how to obtain the class type from a string, which can be obtained by: 我已经在这里问了一个问题如何从字符串中获取类类型,可以通过以下方式获取:

let objectType = NSClassFromString("MyModule.\(strFromLog)”) as! Object.Type

Obviously, objectType can not be used directly on MyClass since it is of type T.Type and not T , and the following does not work: 显然, objectType不能直接在MyClass上使用,因为它的类型为T.Type而不是T ,并且以下内容不起作用:

MyClass<objectType>.doSomething() // -> error: Use of undeclared type 'objectType'

However, is there still a way to use objectType in MyClass without the need to change the generic class itself (ie other methods rely on it)? 但是,还有没有一种方法可以在MyClass使用objectType而不需要更改泛型类本身(即其他方法依赖它)?

Unfortunately you can't use result of NSClassFromString as a type for your generic class. 不幸的是,您不能将NSClassFromString结果用作泛型类的类型。 However, you can workaround this by writing something like this: 但是,您可以通过编写以下代码来解决此问题:

protocol SomeProtocol {
}

extension NSString: SomeProtocol {
}

class SomeClass<T: SomeProtocol> {
  class func doSomething() {
  }
}

if let some = NSClassFromString("NSString") {
  if some is NSString.Type {
    SomeClass<NSString>.doSomething()
    print("String")
  } else {
    print("Not String")
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM