ios - 如何获取带有命名空间(或框架名称)的字符串形式的 Swift 类型名称

标签 ios swift

有没有办法以字符串形式获取 Swift 类型名称及其命名空间(或框架名称)?

例如,如果 Foo.framework 有一个名为 Bar 的类,我想得到一个类似 "Foo.Bar" 的字符串>.

以下代码仅返回类名“Bar”

let barName1 = String(Bar.self)       // returns "Bar"
let barName2 = "\(Bar.self)"          // returns "Bar"
let barName3 = "\(Bar().dynamicType)" // returns "Bar"

我还想将框架名称“Foo”作为命名空间。

最佳答案

使用String(reflecting:) :

struct Bar { }

let barName = String(reflecting: Bar.self) 
print(barName) // <Module>.Bar

来自Xcode 7 Release Notes :

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.

关于ios - 如何获取带有命名空间(或框架名称)的字符串形式的 Swift 类型名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57368896/

相关文章:

ios - 无法将类型 '[SomeStruct]' 的值转换为指定类型 '[SomeProtocol]'

Swift 5 Ubuntu 16.04 因 dateComponents 崩溃

ios - 为什么 NSString 不响应选择器 longValue 但响应 longLongValue 和 intValue?

ios - 接收器没有标识符为 'goToDetail' 的 Segue

swift - 如何在不复制的情况下将 `Data` 对象放入 Swift-NIO 中?

ios - 注册时获取可选值崩溃

ios - SwiftUI 工作表 : Inconsistent sheet behaviour with navigationBarItems

ios - 是否可以在应用程序运行时在设备上训练 CoreML 模型?

iphone - 更改 UIVIEW 的变换/旋转/缩放而不使用动画

ios - 有没有办法检查字符串是否包含 Unicode 字母?