如何使用其命名空间(或框架名称)将Swift类型名称作为字符串 [英] How to get a Swift type name as a string with its namespace (or framework name)
问题描述
有没有办法将Swift类型名称作为带有命名空间(或框架名称)的字符串?
Is there any way to get a Swift type name as a string with its namespace (or framework name)?
例如,如果 Foo.framework
有一个名为 Bar
的类,我想得到类似Foo.Bar的字符串
。
For example, if Foo.framework
has a class named Bar
, I would like to get a string something like "Foo.Bar"
.
以下内容只返回班级名称Bar
。
The followings just return the class name "Bar"
.
let barName1 = String(Bar.self) // returns "Bar"
let barName2 = "\(Bar.self)" // returns "Bar"
let barName3 = "\(Bar().dynamicType)" // returns "Bar"
我想将框架名称Foo
作为命名空间。
I would like to also get the framework name "Foo"
as a namespace.
推荐答案
使用 字符串(反映:)
:
struct Bar { }
let barName = String(reflecting: Bar.self)
print(barName) // <Module>.Bar
来自 Xcode 7发行说明:
类型名称和enum case现在打印并转换为String,默认情况下不带
限定。debugPrint
或字符串(反映:)
仍可使用
来获取完全限定名称。
Type names and enum cases now print and convert to String without qualification by default.
debugPrint
orString(reflecting:)
can still be used to get fully qualified names.
这篇关于如何使用其命名空间(或框架名称)将Swift类型名称作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!