如何在Swift中将UIColor用作枚举类型的RawValue

jac*_*ujh 4 enums uikit uicolor swift

我试图使用UIColor作为原始值声明一个枚举类型。这是代码:

enum SGColor: UIColor {
    case red = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
    case green = #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
    case purple = #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
}
Run Code Online (Sandbox Code Playgroud)

但是第一行出现了两个错误:

'SGColor' declares raw type 'UIColor', but does not conform to
RawRepresentable and conformance could not be synthesized
Run Code Online (Sandbox Code Playgroud)

是否要添加协议存根? Fix it

Raw type 'UIColor' is not expressible by any literal
Run Code Online (Sandbox Code Playgroud)

如果我接受了第一个建议,则Xcode将添加typealias RawValue = <#type#>在括号内的开头。但是我不确定该怎么办。如果要解决第二个错误,如何将原始类型更改为文字?

jac*_*ujh 5

经过一番挖掘,我发现Ole Begemann的帖子提到了如何制作自定义的颜色枚举集合,SGColor在这个问题上,该集合符合RawRepresentable协议。

基本上,虽然Xcode聪明地建议我通过显式地告诉它原始类型来解决该问题(如问题中的第一个错误所示),但它仍然不够聪明,无法弄清楚如何对颜色文字进行处理,或者UIColor。

Ole Begemann提到手动一致性将解决此问题。他还详细说明了如何执行此操作。

在他使用UIColor颜色对象(例如UIColor.red)的同时,我尝试并测试了使用颜色文字的可行性,因为总的来说,它们在视觉上更直观,更可定制。

enum SGColor {
    case red
    case green
    case purple
}
extension SGColor: RawRepresentable {
    typealias RawValue = UIColor

    init?(rawValue: RawValue) {
        switch rawValue {
        case #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1): self = .red
        case #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1): self = .green
        case #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1): self = .purple
        default: return nil
        }
    }

var rawValue: RawValue {
        switch self {
        case .red: return #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1)
        case .green: return #colorLiteral(red: 0.4666666687, green: 0.7647058964, blue: 0.2666666806, alpha: 1)
        case .purple: return #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)