【问题标题】:Swift - getting generic type's classSwift - 获取泛型类型的类
【发布时间】:2014-10-06 07:34:29
【问题描述】:

我有非常基本的模型,比如

class Model {

}

class User : Model {

} 

class Group : Model {

}

现在我需要检查泛型类型以了解哪个类作为参数发送

func getRepository<ModelType: Model>() {
   if (typeof(ModelType) == User.self) {
       // Do something specific to User
   } else {
       .....
   }
}

但我不知道如何获取 GENERIC TYPE 的类。

非常感谢您的回答。

干杯

【问题讨论】:

  • 你打算如何调用这个函数?
  • 除非您将参数传递给getRepository,否则编译器无法推断ModelType 的类型(除了某种Model)。如果您尝试调用 getRepository() 并像这样定义它(即使其中没​​有任何内容),您将收到编译错误。我猜你实际上想要这样的东西:func getRepository&lt;ModelType: Model&gt;(model: ModelType)?
  • @JoachimIsaksson 我打算将其称为getRepository&lt;User&gt;()
  • @MikeS getRepository&lt;ModelType: Model&gt;(model: ModelType) 看起来很丑,你不觉得吗?我应该能够像 C# 一样获得通用类型

标签: generics swift


【解决方案1】:

这个https://gist.github.com/MartinJNash/e2bb27937711f350aa44怎么样?我不确定它是否有效,但想法是获取字符串中的类名然后比较它们:

class Model {
    class func classString() -> String {
        return NSStringFromClass(self)
    }
}


func getRepository<ModelType: Model>() {
   if (ModelType.classString() == User.classString()) {
       // ...
   }
}

【讨论】:

  • 谢谢@blue-smith!现在这对我来说似乎是一个解决方案。
猜你喜欢
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-20
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多