0
我正在編寫一個日誌記錄類,以便在我的項目中使用,基於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)
}
這些都做工精細,但我覺得代碼太重複,想使用通用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,我發現,我試圖做的事情可以實現,它不能,到目前爲止,我只證明它不能做。
有人能指出我如何做到這一點的正確方向嗎?謝謝。
你可以只通過枚舉作爲函數參數。 – ryantxr