获取对象的类名为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()))"

其他回答

斯威夫特5

下面是将typeName作为变量获取的扩展(使用值类型或引用类型)。

protocol NameDescribable {
    var typeName: String { get }
    static var typeName: String { get }
}

extension NameDescribable {
    var typeName: String {
        return String(describing: type(of: self))
    }

    static var typeName: String {
        return String(describing: self)
    }
}

使用方法:

// Extend with class/struct/enum...
extension NSObject: NameDescribable {}
extension Array: NameDescribable {}
extension UIBarStyle: NameDescribable { }

print(UITabBarController().typeName)
print(UINavigationController.typeName)
print([Int]().typeName)
print(UIBarStyle.typeName)

// Out put:
UITabBarController
UINavigationController
Array<Int>
UIBarStyle

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

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

在我的例子中,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也可以。上面的函数也是故障安全的:)

以上的解决方案对我不起作用。产生的主要问题在几个评论中提到:

MyAppName。类名称

or

MyFrameWorkName。类名称

这个解决方案适用于XCode 9, Swift 3.0:

我把它命名为classnamecinclined,这样更容易访问,也不会与未来的className()更改冲突:

extension NSObject {

static var classNameCleaned : String {

    let className = self.className()
    if className.contains(".") {
        let namesArray = className.components(separatedBy: ".")
        return namesArray.last ?? className
    } else {
        return self.className()
    }

}

}

用法:

NSViewController.classNameCleaned
MyCustomClass.classNameCleaned

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

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
}