在swift中获取类名的用户可读版本(在objc NSStringFromClass中很好) [英] Get a user-readable version of the class name in swift (in objc NSStringFromClass was fine)

查看:199
本文介绍了在swift中获取类名的用户可读版本(在objc NSStringFromClass中很好)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中有一个等价的NSStringFromClass,提供类名的用户可读版本?我试图用我创建的一个原生Swift类使用它,但是你可以看到,结果似乎是编译器的类名称的内部表示:

Is there an equivalent of NSStringFromClass in Swift that gives a user-readable version of the class name? I've tried to use it with a native Swift class I created, but as you can see, the result seems to be the compiler's internal representation of the class name:

println(NSStringFromClass(MyClass.self))

/ p>

Result:

_TtC5test7MyClass

我试过将 @objc 属性添加到类中,并将其作为NSObject的子类,但它没有什么区别。我发现如果我用一个相同名称的Objective-C类替换MyClass,并将其导入桥接头,它给我'MyClass',但这不是必要的。

I've tried adding the @objc attribute to the class, and making it a subclass of NSObject, but it makes no difference. I've discovered that if I replace MyClass with an Objective-C class of the same name, and import this in the bridging header, it gives me 'MyClass', but this shouldn't be necessary.

另一个选择是为这个协议,我想使用这种方式每个类必须符合:

Another option would be to make a protocol for this, which each class I want to use in this way must conform to:

protocol Nameable {
    class var className: String { get }
}


推荐答案

但是, >基于xcode 6 beta 5的新格式。

new format based on xcode 6 beta 5.

(project_name)

(project_name).(class_name)

func getName(classType:AnyClass) -> String {

    let classString = NSStringFromClass(classType.self)
    let range = classString.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch, range: Range<String.Index>(start:classString.startIndex, end: classString.endIndex), locale: nil)
    return classString.substringFromIndex(range!.endIndex)
}

最新6.3 Xcode Swift 1.2

Latest 6.3 Xcode Swift 1.2

如果你需要一个扩展或者你可以把它放在任何通用对象: / p>

if you need an extension or you can put this on any common object:

public extension NSObject{
    public class var nameOfClass: String{
        return NSStringFromClass(self).componentsSeparatedByString(".").last!
    }

    public var nameOfClass: String{
        return NSStringFromClass(self.dynamicType).componentsSeparatedByString(".").last!
    }
}

这篇关于在swift中获取类名的用户可读版本(在objc NSStringFromClass中很好)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆