I want to return a RawRepresentable's rawValue as an Any, but I only receive it as an Any

383 Views Asked by At

so I have a function which receives an Any and it checks if the Any is an enum by using reflection:

func extractRawValue(subject: Any) throws -> Any {
    let mirror = Mirror(reflecting: subject)

    guard let displayStyle = mirror.displayStyle,
        case .`enum` = displayStyle else {
            throw Errors.NoEnum
    }

    // And from here I don't know how to go any further...
    // I wish I could do something like this:
    guard let subject = subject as? RawRepresentable where let rawValue = subject.rawValue as Any else {
        throw Errors.NoRawRepresenable
    }

    return rawValue 
}

Does anyone know how I can accomplish something like that?

1

There are 1 best solutions below

2
On

I think the Swifty way to do this is to use a protocol for the enums you want to use:

protocol ValueAsAnyable {
    func valueAsAny() -> Any
}

extension ValueAsAnyable where Self: RawRepresentable {
    func valueAsAny() -> Any {
        return rawValue as Any
    }
}

func extractRawValue(subject: Any) throws -> Any {
    let mirror = Mirror(reflecting: subject)

    guard let displayStyle = mirror.displayStyle,
        case .`enum` = displayStyle else {
            throw Errors.NoEnum
    }
    guard let anyable = subject as? ValueAsAnyable else {
        throw Errors.NoRawRepresentable
    }
    return anyable.valueAsAny()
}

let subject: Any = TestEnum.test
let thing = try? extractRawValue(subject: subject) //prints "test"

This should allow you to do what you need, but keep Type safety.