如何使用其命名空间(或框架名称)将Swift类型名称作为字符串 [英] How to get a Swift type name as a string with its namespace (or framework name)

查看:96
本文介绍了如何使用其命名空间(或框架名称)将Swift类型名称作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将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 or String(reflecting:) can still be used to get fully qualified names.

这篇关于如何使用其命名空间(或框架名称)将Swift类型名称作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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