获取对象的类名为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也可以。上面的函数也是故障安全的:)
其他回答
在Swift 4.1和现在的Swift 4.2中:
import Foundation
class SomeClass {
class InnerClass {
let foo: Int
init(foo: Int) {
self.foo = foo
}
}
let foo: Int
init(foo: Int) {
self.foo = foo
}
}
class AnotherClass : NSObject {
let foo: Int
init(foo: Int) {
self.foo = foo
super.init()
}
}
struct SomeStruct {
let bar: Int
init(bar: Int) {
self.bar = bar
}
}
let c = SomeClass(foo: 42)
let s = SomeStruct(bar: 1337)
let i = SomeClass.InnerClass(foo: 2018)
let a = AnotherClass(foo: 1<<8)
如果你周围没有实例:
String(describing: SomeClass.self) // Result: SomeClass
String(describing: SomeStruct.self) // Result: SomeStruct
String(describing: SomeClass.InnerClass.self) // Result: InnerClass
String(describing: AnotherClass.self) // Result: AnotherClass
如果你有一个实例:
String(describing: type(of: c)) // Result: SomeClass
String(describing: type(of: s)) // Result: SomeStruct
String(describing: type(of: i)) // Result: InnerClass
String(describing: type(of: a)) // Result: AnotherClass
Swift 5.1:-
你也可以使用泛型函数获取对象的类名作为字符串
struct GenericFunctions {
static func className<T>(_ name: T) -> String {
return "\(name)"
}
}
使用以下方法调用此函数:-
let name = GenericFunctions.className(ViewController.self)
快乐编码:)
来自实例的字符串:
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类的名称,例如var object: SomeClass(),使用
String(describing: type(of: object))
要从类类型中获取Swift类的名称,例如SomeClass,使用:
String(describing: SomeClass.self)
输出:
" SomeClass "
我一直在断断续续地寻找这个答案。我使用GKStateMachine,喜欢观察状态变化,想要一种简单的方法来查看类名。我不确定它是iOS 10还是Swift 2.3,但在这种环境下,以下内容正是我想要的:
let state:GKState?
print("Class Name: \(String(state.classForCoder)")
// Output:
// Class Name: GKState