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

object_getClassName(myViewController)

返回如下内容:

_TtC5AppName22CalendarViewController

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

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


当前回答

要在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()))"

其他回答

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

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
}

如果你的类型是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:)部分。

斯威夫特3.0

字符串(描述:MyViewController.self)

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)

快乐编码:)