[英]Is there a clean way of making an enum with associated value conform to rawRepresentable?
I have this in my code and it works, however if I have other enums (not necessarily color) with a long list it gets tiresome.我在我的代码中有这个并且它可以工作,但是如果我有其他枚举(不一定是颜色)并且列表很长,它会变得很烦人。 Is there a better way of having an enum with an associated value that also conforms to RawRepresentable?
有没有更好的方法让枚举具有也符合 RawRepresentable 的关联值?
public enum IconColor {
case regular
case error
case warning
case success
case custom(String)
public var value: Color {
return loadColor(self.rawValue)
}
}
extension IconColor: RawRepresentable {
public var rawValue: String {
switch self {
case .regular: return "icon_regular"
case .error: return "icon_error"
case .warning: return "icon_warning"
case .success: return "icon_success"
case .custom(let value): return value
}
}
public init(rawValue: String) {
switch rawValue {
case "icon_regular": self = .regular
case "icon_error": self = .error
case "icon_warning": self = .warning
case "icon_success": self = .success
default: self = .custom(rawValue)
}
}
}
There's not a general solution.没有一个通用的解决方案。
public var rawValue: String {
switch self {
case .custom(let value): return value
default: return "icon_\(self)"
}
}
public init(rawValue: String) {
self =
[.regular, .error, .warning, .success]
.first { rawValue == $0.rawValue }
?? .custom(rawValue)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.