获取对象的类名为String,使用:

object_getClassName(myViewController)

返回如下内容:

_TtC5AppName22CalendarViewController

我正在寻找纯粹的版本:“CalendarViewController”。我如何得到一个清理类名字符串代替?

我发现了一些关于这个问题的尝试,但没有一个实际的答案。难道根本不可能吗?


当前回答

我一直在断断续续地寻找这个答案。我使用GKStateMachine,喜欢观察状态变化,想要一种简单的方法来查看类名。我不确定它是iOS 10还是Swift 2.3,但在这种环境下,以下内容正是我想要的:

let state:GKState?
print("Class Name: \(String(state.classForCoder)")

// Output:    
// Class Name: GKState

其他回答

你可以通过如下方式获取类名:

class Person {}
String(describing: Person.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 5.1:-

你也可以使用泛型函数获取对象的类名作为字符串

struct GenericFunctions {
 static func className<T>(_ name: T) -> String {
        return "\(name)"
    }

}

使用以下方法调用此函数:-

let name = GenericFunctions.className(ViewController.self)

快乐编码:)

如果你的类型是Foo,下面的代码会在Swift 3和Swift 4中给你“Foo”:

let className = String(describing: Foo.self) // Gives you "Foo"

这里大多数答案的问题是,他们给你“Foo”。当你没有该类型的任何实例时,当你真正想要的只是"Foo"时,输入"作为结果字符串。下面是“Foo”。输入“”,就像在其他答案中提到的那样。

let className = String(describing: type(of: Foo.self)) // Gives you "Foo.Type"

如果您只想要“Foo”,则不需要使用类型(of:)部分。

你可以试试这种方法:

self.classForCoder.description()