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

object_getClassName(myViewController)

返回如下内容:

_TtC5AppName22CalendarViewController

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

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


当前回答

这个解决方案适用于所有的类

Swift 5解决方案:

extension NSObject {
  var className: String {
    return String(describing: type(of: self))
  }

  class var className: String {
    return String(describing: self)
  }
}

用法:

class TextFieldCell: UITableVIewCell {
}

class LoginViewController: UIViewController {
  let cellClassName = TextFieldCell.className
}

其他回答

斯威夫特5

 NSStringFromClass(CustomClass.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标准库函数_stdlib_getDemangledTypeName:

let name = _stdlib_getDemangledTypeName(myViewController)

Swift 3.0 (macOS 10.10及更高版本),你可以从className中获取它

self.className.components(separatedBy: ".").last!

Swift 5.1:-

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

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

}

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

let name = GenericFunctions.className(ViewController.self)

快乐编码:)