因为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<Int>
UIBarStyle

文章介绍了如何在Swift中通过扩展NSObject来获取其子类的类名,包括使用`NSStringFromClass`方法和自定义协议`NameDescribable`。此外,还展示了如何为不同类型如数组、枚举等添加这个功能。
4593

被折叠的 条评论
为什么被折叠?



