本文介绍了在Swift中以字符串形式获取对象的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 String
获取对象的类名:
Getting the classname of an object as String
using:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯版本:"CalendarViewController"
.我如何获得清理的类名字符串?
I am looking for the pure version: "CalendarViewController"
. How do I get a cleaned up string of the class name instead?
我发现了一些有关此问题的尝试,但没有找到实际答案.完全不可能吗?
I found some attempts of questions about this but not an actual answer. Is it not possible at all?
推荐答案
实例中的字符串:
String(describing: self)
来自类型的字符串:
String(describing: YourType.self)
示例:
struct Foo {
// Instance Level
var typeName: String {
return String(describing: Foo.self)
}
// Instance Level - Alternative Way
var otherTypeName: String {
let thisType = type(of: self)
return String(describing: thisType)
}
// Type Level
static var typeName: String {
return String(describing: self)
}
}
Foo().typeName // = "Foo"
Foo().otherTypeName // = "Foo"
Foo.typeName // = "Foo"
使用 class
、struct
和 enum
进行测试.
Tested with class
, struct
and enum
.
这篇关于在Swift中以字符串形式获取对象的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!