XZ_Swift 在Swift中以字符串形式获取对象的类名

因为NSObject是大多数Objective-C类层次结构的根类,所以可以尝试对NSObject进行扩展,以获取NSObject的每个子类的类名:

extension NSObject {
    var theClassName: String {
        return NSStringFromClass(type(of: self))
    }
}

// 调用
let button = UIButton(type: .custom)
let responderName = button.theClassName
print("-----responderName:", responderName) // 打印结果: UIButton

或者可以创建一个静态函数,其参数类型为Any (The protocol to which all types implicitly conform),并以字符串形式返回类名:

class Utility{
    class func classNameAsString(_ obj: Any) -> String {
        //prints more readable results for dictionaries, arrays, Int, etc
        return String(describing: type(of: obj))
    }
} 

下面是将typeName作为变量(work with both value type or reference type)的扩展

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
UIBarStyle

你可能感兴趣的:(iOS,Swift,swift,ios,开发语言)