gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:52:13 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com