在Swift中打印当前模块名

nnt7mjpx  于 9个月前  发布在  Swift
关注(0)|答案(5)|浏览(91)

如何在Swift中打印类的模块名?
self.dynamicType只打印类名而不打印模块。如何打印模块?

brtdzjyr

brtdzjyr1#

对于不那么漂亮但目前有效的方法,请尝试:

let object = NSStringFromClass(MyClass) as NSString
let module = object.componentsSeparatedByString(".").first!

字符串
不过,这似乎不适用于Foundation/UIKit等对象

rjee0c15

rjee0c152#

这里有一个不同的解决方案

// "To parse a #fileID expression, read the module name as the text before the first slash (/) and the filename as the text after the last slash"
func moduleName(fileId: String = #fileID) -> String? {
   fileId.firstIndex(of: "/").flatMap { String(fileId[fileId.startIndex ..< $0]) }
}

字符串

0g0grzrc

0g0grzrc3#

还有一种打印当前模块名的方法.在Swift中。

let module = String(String(reflecting: MY_SUBJECT.self).prefix { $0 != "." })

字符串

iecba09b

iecba09b4#

这里有一个替代方案,它不使用NSString/Obj-C代码,而是纯Swift(因此更快且跨平台):

let moduleName = String(reflecting: Self.self)
    .split(separator: ".", maxSplits: 1).first ?? ""

字符串

xwbd5t1u

xwbd5t1u5#

您可以通过以下简单代码从#fileID宏中提取模块名称,该宏包含module/file形式的唯一标识符:

let moduleName = NSString(#fileID).pathComponents.first!

字符串

相关问题