Search code examples
swiftenumsassociated-valuerawrepresentable

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?

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

Solution

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