2017-08-12 60 views
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,我發現,我試圖做的事情可以實現,它不能,到目前爲止,我只證明它不能做。

有人能指出我如何做到這一點的正確方向嗎?謝謝。

+2

你可以只通過枚舉作爲函數參數。 – ryantxr

回答

3

錯誤消息說您不能使用枚舉作爲通用約束。

其實你並不需要一個通用的功能,通過水平作爲參數,例如

class public func log(level: LogLevelGeneric, items: Any..., separator: String = "", _ file: String = #file, _ line: Int = #line, _ function: String = #function) { 


} 
+0

doh!即時通訊愚蠢,我是如此專注於學習泛型,我甚至懶得退後一步。謝謝! – highboi