Is there a cleaner way of making an enum with associated value conform to rawRepresentable?

I have this in my code and it works, however if I have a long list it gets tiresome. Is there a better way of having an enum with associated values 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)
		}
	}
}

I do not see what you want to simplify. Except put the extension directly in the enum definition…

It's not exactly what you were looking for, but maybe you can make this work?

public enum IconColor {
    public enum Standard: String {
        case regular = "icon_regular"
        case error = "icon_error"
        case warning = "icon_warning"
        case success = "icon_success"
    }

    case standard(Standard)
    case custom(String)

    public var rawValue: String {
        switch self {
        case .standard(let standardCase):
            return standardCase.rawValue
        case .custom(let value):
            return value
        }
    }
}

Then it could be used like this:

let x = IconColor.Standard.success
let y = IconColor.custom("icon_deviceonfire")

print(x.rawValue)    // Prints "icon_success"
print(y.rawValue)    // Prints "icon_deviceonfire"

Here's another one I came up with, using struct instead of enum:

public struct IconColor: RawRepresentable {
    public enum StandardColors: String {
        case regular = "icon_regular"
        case error = "icon_error"
        case warning = "icon_warning"
        case success = "icon_success"
    }

    public var rawValue: String

    public init(rawValue: String) {
        self.rawValue = rawValue
    }

    public init(_ standardValue: StandardColors) {
        self.rawValue = standardValue.rawValue
    }

    public init(_ customValue: String) {
        self.rawValue = customValue
    }
}

// ...

let successColor = IconColor(.success)
let customColor = IconColor("icon_custom")
var rawCustomColor = IconColor(rawValue: "icon_rawcustom")
Is there a cleaner way of making an enum with associated value conform to rawRepresentable?
 
 
Q