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

object_getClassName(myViewController)

返回如下内容:

_TtC5AppName22CalendarViewController

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

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


当前回答

斯威夫特5.1

你可以通过Self.self获取类、结构、枚举、协议和NSObject名称。

print("\(Self.self)")

其他回答

你可以像这样使用Swift标准库函数_stdlib_getDemangledTypeName:

let name = _stdlib_getDemangledTypeName(myViewController)

有时其他解决方案会给出一个无用的名称,这取决于您试图查看的对象。在这种情况下,您可以使用以下命令获取类名作为字符串。

String(cString: object_getClassName(Any!))

⌘单击xcode中的函数,查看一些相当有用的相关方法。或者点击这里查看https://developer.apple.com/reference/objectivec/objective_c_functions

我建议这样的方法(非常Swifty):

// Swift 3
func typeName(_ some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}

// Swift 2
func typeName(some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}

它既不使用内省,也不使用手动提取(没有魔法!)


下面是一个演示:

// Swift 3

import class Foundation.NSObject

func typeName(_ some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(type(of: some))"
}

class GenericClass<T> {
    var x: T? = nil
}

protocol Proto1 {
    func f(x: Int) -> Int
}


@objc(ObjCClass1)
class Class1: NSObject, Proto1 {
    func f(x: Int) -> Int {
        return x
    }
}

struct Struct1 {
    var x: Int
}

enum Enum1 {
    case X
}

print(typeName(GenericClass<Int>.self)) // GenericClass<Int>
print(typeName(GenericClass<Int>()))  // GenericClass<Int>

print(typeName(Proto1.self)) // Proto1

print(typeName(Class1.self))   // Class1
print(typeName(Class1())) // Class1
print(typeName(Class1().f)) // (Int) -> Int

print(typeName(Struct1.self)) // Struct1
print(typeName(Struct1(x: 1))) // Struct1
print(typeName(Enum1.self)) // Enum1
print(typeName(Enum1.X)) // Enum1

你也可以使用镜子:

let vc = UIViewController()

String(Mirror(reflecting: vc).subjectType)

注意:此方法也可用于结构和枚举。有一个displayStyle指示结构的类型:

Mirror(reflecting: vc).displayStyle

返回值是一个枚举,所以你可以:

Mirror(reflecting: vc).displayStyle == .Class

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