swift - 我如何在泛型类中使用枚举值

标签 swift generics

我正在编写一个日志记录类以在我基于 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   "
}

搜索google和stackoverflow,我发现我想做的事情可以实现,但不能实现,到目前为止我只是证明它不能完成。

有人能指出正确的方向吗?谢谢。

最佳答案

错误消息说您不能将枚举用作通用约束。

实际上你不需要通用函数,例如将级别作为参数传递

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


}

关于swift - 我如何在泛型类中使用枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45654659/

相关文章:

swift - 使用 NSURLSession HTTP Post 发送 Firebase Swift 推送

ios - RxSwift 观察数组变化

swift - 尝试在 tvOS 上输入文本时,UISearchController 与 UIAlertController 结合出现问题

extension-methods - 将泛型扩展方法限制为基本类型和字符串

c# - 为什么 List<T> 在协变接口(interface) MyInterface<out T> 上无效

ios - 如何实现验证现有用户名

swift - 协议(protocol)类型的调用方法

c# - 将派生类转换为基类可以在使用泛型时保留派生知识

java - Java 中的泛型 - 与遗留代码互操作

c# - 如何使泛型类的类型可转换?