获取对象的类名为String,使用:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?
我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?
获取对象的类名为String,使用:
object_getClassName(myViewController)
返回如下内容:
_TtC5AppName22CalendarViewController
我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?
我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?
当前回答
在我的例子中,String(description: self)返回如下内容:
< My_project。ExampleViewController: 0x10b2bb2b0 >
但我想在Android上有类似getSimpleName的东西。
所以我创建了一个小扩展:
extension UIViewController {
func getSimpleClassName() -> String {
let describing = String(describing: self)
if let dotIndex = describing.index(of: "."), let commaIndex = describing.index(of: ":") {
let afterDotIndex = describing.index(after: dotIndex)
if(afterDotIndex < commaIndex) {
return String(describing[afterDotIndex ..< commaIndex])
}
}
return describing
}
}
现在它返回:
ExampleViewController
扩展NSObject而不是UIViewController也可以。上面的函数也是故障安全的:)
其他回答
来自实例的字符串:
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"
用类、结构和enum测试。
要在Swift 4中获得类型名为字符串(我没有检查早期版本),只需使用字符串插值:
"\(type(of: myViewController))"
你可以在类型本身上使用.self,在实例上使用type(of:_)函数:
// Both constants will have "UIViewController" as their value
let stringFromType = "\(UIViewController.self)"
let stringFromInstance = "\(type(of: UIViewController()))"
你也可以使用镜子:
let vc = UIViewController()
String(Mirror(reflecting: vc).subjectType)
注意:此方法也可用于结构和枚举。有一个displayStyle指示结构的类型:
Mirror(reflecting: vc).displayStyle
返回值是一个枚举,所以你可以:
Mirror(reflecting: vc).displayStyle == .Class
斯威夫特5.1
你可以通过Self.self获取类、结构、枚举、协议和NSObject名称。
print("\(Self.self)")
要获得类名为String,请按以下方式声明类
@objc(YourClassName) class YourClassName{}
并使用以下语法获取类名
NSStringFromClass(YourClassName)