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

标签 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 
}

有谁知道我怎样才能完成这样的事情?

最佳答案

我认为执行此操作的 Swifty 方法是为您要使用的枚举使用协议(protocol):

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"

这应该允许你做你需要的,但保持类型安全。

关于swift - 我想将 RawRepresentable 的 rawValue 作为 Any 返回,但我只将它作为 Any 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40535502/

相关文章:

swift - 如何根据目标有选择地导入 Swift 中的模块?

swift - 字节转换为字符串 swift(或 swift2)

java - 如何获取参数化类型的类引用

validation - 在 Kotlin 中,根据属性的类型限制注解目标

c# - 枚举扩展方法 – ToDataSource

c - 以下关于 C 编程中枚举的含义是什么?

swift - 使用 NSObject 上的简单 Swift 扩展编译错误

ios - 使用 Alamofire 从 Firebase 检索 JSON

c# - 如何获取基类的所有继承类?

java - For 循环嵌套在 do... while 不起作用