我想将RawRepresentable的rawValue作为Any返回,但我只接收它作为Any

时间:2016-11-10 19:26:51

标签: swift reflection enums rawrepresentable

所以我有一个接收Any的函数,它通过反射检查Any是否为枚举:

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 
}

有谁知道我怎么能做到这样的事情?

1 个答案:

答案 0 :(得分:2)

我认为Swifty这样做的方法是为你想要使用的枚举使用协议:

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"

这应该可以让你做你需要的,但保持类型安全。