我正在编写一个基于Log的项目中使用的日志记录类。
在Log
中,日志记录方法就像这样调用
open func trace(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.trace, items, separator, terminator, file, line, column, function)
}
open func debug(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.debug, items, separator, terminator, file, line, column, function)
}
open func info(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.info, items, separator, terminator, file, line, column, function)
}
open func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.warning, items, separator, terminator, file, line, column, function)
}
open func error(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(.error, items, separator, terminator, file, line, column, function)
}
这些都可以正常工作,但我发现代码过于重复,并希望使用Generic T
类型的单一方法替换它
open func log<T: Level>(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) {
log(T, items, separator, terminator, file, line, column, function)
}
我提出的方法是
class public func log<T: LogLevelGeneric>(_ items: Any..., separator: String = "", _ file: String = #file, _ line: Int = #line, _ function: String = #function, t:T) {
// Error: Inheritance from non-protocol, non-class type LogLevelGeneric
}
public enum LogLevelGeneric: String {
case pretty = "Prettify"
case measure = "Measure "
case verbose = "Verbose "
case info = "Info "
case warning = "Warning "
case debug = "Debug "
case error = "❤️️Error "
}
搜索谷歌和stackoverflow,香港专业教育学院发现我试图做的事情可以实现,但它不能,到目前为止我只是证明它无法完成。
有人能指出我如何做到这一点的正确方向?感谢。
答案 0 :(得分:3)
错误消息表明您不能将枚举用作通用约束。
实际上,您不需要通用功能,将该级别作为参数传递,例如
class public func log(level: LogLevelGeneric, items: Any..., separator: String = "", _ file: String = #file, _ line: Int = #line, _ function: String = #function) {
}