在Swift中获取泛型类型的名称(字符串) [英] Get the name (string) of a generic type in Swift
问题描述
我有一个T类型的泛型类,我希望获得实例化时传入类的类型的名称。这是一个例子。
class MyClass< T> {
func genericName() - >字符串{
//返回T.
}的名称
}
我一直在找几个小时,我似乎无法找到任何方法来做到这一点。有没有人试过这个呢?
任何帮助都非常感谢。
谢谢
可能的解决方法是: / p>
class MyClass< T:AnyObject> {
func genericName() - > String {
let fullName:String = NSStringFromClass(T.self)
let range = fullName.rangeOfString(。,options:.BackwardsSearch)
if range = range {
return fullName.substringFromIndex(range.endIndex)
} else {
return fullName
}
}
}
限制依赖于它仅适用于类的事实。
如果这是通用的键入:
class TestClass {}
NSStringFromClass()
返回全名(包括名称空间):
//在操场中打印类似__lldb_expr_186.TestClass的东西
NSStringFromClass(TestClass.self)
这就是为什么func会搜索。
字符的最后一次出现。
测试如下:
var x = MyClass< TestClass> ;()
x.genericName()//打印TestClass
UPDATE Swift 3.0
func genericName() - > String {
let fullName:String = NSStringFromClass(T.self)
let range = fullName.range(of:。)
if range = range {
return fullName .substring(from:range.upperBound)
}
return fullName
}
I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example.
class MyClass<T> {
func genericName() -> String {
// Return the name of T.
}
}
I have been looking around for hours and I can't seem to find any way to do this. Has anyone tried this yet?
Any help is greatly appreciated.
Thanks
A pure swift way to achieve that is not possible.
A possible workaround is:
class MyClass<T: AnyObject> {
func genericName() -> String {
let fullName: String = NSStringFromClass(T.self)
let range = fullName.rangeOfString(".", options: .BackwardsSearch)
if let range = range {
return fullName.substringFromIndex(range.endIndex)
} else {
return fullName
}
}
}
The limitations relies on the fact that it works with classes only.
If this is the generic type:
class TestClass {}
NSStringFromClass()
returns the full name (including namespace):
// Prints something like "__lldb_expr_186.TestClass" in playground
NSStringFromClass(TestClass.self)
That's why the func searches for the last occurrence of the .
character.
Tested as follows:
var x = MyClass<TestClass>()
x.genericName() // Prints "TestClass"
UPDATE Swift 3.0
func genericName() -> String {
let fullName: String = NSStringFromClass(T.self)
let range = fullName.range(of: ".")
if let range = range {
return fullName.substring(from: range.upperBound)
}
return fullName
}
这篇关于在Swift中获取泛型类型的名称(字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!