【问题标题】:Swift: obtain module at runtime?Swift:在运行时获取模块?
【发布时间】:2021-11-17 21:35:33
【问题描述】:

在 Swift 中,在运行时,是否可以知道正在运行的模块代码的名称?

我想要类似的东西(这完全是虚构的代码)

let moduleName: String = CompileTimeInfo.moduleName

Related.

【问题讨论】:

  • 你需要这个做什么?
  • 这将有助于构建设置的运行时验证。

标签: swift reflection module runtime


【解决方案1】:

您可能会利用模块名称用作命名空间这一事实,debugPrint 类型将以模块名称为前缀:

enum Test {}
var string: String = ""
debugPrint(Test.self, to: &string)     
print("Module name: \(string.split(separator: ".").first ?? "")")

注意:类型必须在实际模块中定义。因此,将前三行包装成一个函数并返回模块名称,完成。

【讨论】:

  • 这是一个非常有创意的 hack,kudosthanks!
【解决方案2】:

借鉴@CouchDeveloper 的出色answer,您可以获得任意Swift 的模块名称​​type。您可以使用它来获取任意代码的模块名称,为此创建一个类型。

func moduleName(for type: Any.Type) -> String {
  // parse module name from string that looks like "ModuleName.ClassName"
  if let subSequence = String(reflecting: type.self).split(separator: ".").first {
    return String(subSequence)
  } else {
    return ""
  }
}

print(moduleName(for: String.self)) // -> Swift

enum Test {}
print(moduleName(for: Test.self))   // -> SwiftModuleNameExample

这甚至可以嵌入到协议中。

public protocol Module {}
extension Module {
  static var name: String { moduleName(for: Self.self) }
}

class ThisModule: Module {}

print(ThisModule.name)             // -> SwiftModuleNameExample

此代码的 macOS 命令行 Xcode 项目位于 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    相关资源
    最近更新 更多