如何在Swift中打印类的模块名?self.dynamicType只打印类名而不打印模块。如何打印模块?
self.dynamicType
brtdzjyr1#
对于不那么漂亮但目前有效的方法,请尝试:
let object = NSStringFromClass(MyClass) as NSStringlet module = object.componentsSeparatedByString(".").first!
let object = NSStringFromClass(MyClass) as NSString
let module = object.componentsSeparatedByString(".").first!
字符串不过,这似乎不适用于Foundation/UIKit等对象
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]) }}
// "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]) }
}
字符串
0g0grzrc3#
还有一种打印当前模块名的方法.在Swift中。
Swift
let module = String(String(reflecting: MY_SUBJECT.self).prefix { $0 != "." })
iecba09b4#
这里有一个替代方案,它不使用NSString/Obj-C代码,而是纯Swift(因此更快且跨平台):
NSString
let moduleName = String(reflecting: Self.self) .split(separator: ".", maxSplits: 1).first ?? ""
let moduleName = String(reflecting: Self.self)
.split(separator: ".", maxSplits: 1).first ?? ""
xwbd5t1u5#
您可以通过以下简单代码从#fileID宏中提取模块名称,该宏包含module/file形式的唯一标识符:
#fileID
module/file
let moduleName = NSString(#fileID).pathComponents.first!
5条答案
按热度按时间brtdzjyr1#
对于不那么漂亮但目前有效的方法,请尝试:
字符串
不过,这似乎不适用于Foundation/UIKit等对象
rjee0c152#
这里有一个不同的解决方案
字符串
0g0grzrc3#
还有一种打印当前模块名的方法.在
Swift
中。字符串
iecba09b4#
这里有一个替代方案,它不使用
NSString
/Obj-C代码,而是纯Swift(因此更快且跨平台):字符串
xwbd5t1u5#
您可以通过以下简单代码从
#fileID
宏中提取模块名称,该宏包含module/file
形式的唯一标识符:字符串