如何在Swift上打印类名?

sat*_*o94 20 swift

在Swift中,我们不能再使用"self.class"了.

我想在NSObject的子类中为描述方法打印自己的类名.

我该如何打印?或者我应该为获取课程名称制作新方法?


我检查了以下问题,但我无法得到答案.

如何在Swift中打印变量的类型或类?

你如何找到一个对象的类型(在Swift中)?

import UIKit

class PrintClassName: NSObject {
    override init() {
        super.init()
        println("\(self.dynamicType)")
        // Prints "(Metatype)"

        println("\(object_getClassName(self))");
        // Prints "0x7b680910 (Pointer)"

        println("\(self.className)")
        // Compile error!

        println(PrintClassName.self)
        // Prints "(Metatype)"
    }
}
Run Code Online (Sandbox Code Playgroud)

2014.08.25后记

我查了一下这个问题.

Swift类内省和泛型

println(PrintClassName.self)打印"(元型)"

而且我想在不在源代码上编写类名的情况下获取类名.

Ivi*_* M. 39

import Foundation

class PrintClassName : NSObject {
    override init() {
        super.init()
        println(NSStringFromClass(self.dynamicType))
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以使用 - self.className.componentsSeparatedByString(".").last! - 分开你的班级名字 (4认同)