highboi highboi - 2 months ago 15
Swift Question

How can i use an enum value in a generic class

Im writing a logging class to use in my projects based on Log.

In

Log
, the logging methods are called like so

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)
}


These all work fine, but i find the code to be too repetitive and would like to replace it with a single method using a Generic
T
type

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)
}


The method I've come up with is

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 = "

Answer Source

The error message says you can't use an enum as a generic constraint.

Actually you don't need a generic function, pass the level as a parameter for example

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


}