【问题标题】:I want to return a RawRepresentable's rawValue as an Any, but I only receive it as an Any我想将 RawRepresentable 的 rawValue 作为 Any 返回,但我只将它作为 Any 接收
【发布时间】:2016-11-10 19:26:50
【问题描述】:

所以我有一个接收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 
}

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

【问题讨论】:

  • guard let subject = subject as? RawRepresentable where let rawValue = subject.rawValue as Any 想问什么问题?我看到第一部分询问这个东西是否一个 RawRepresentable,但我无法想象第二部分应该是什么意思。在这里帮帮我。
  • 你成功了吗?我试图在这里找到类似的东西:stackoverflow.com/questions/43666118/…

标签: swift reflection enums rawrepresentable


【解决方案1】:

我认为执行此操作的 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"

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

【讨论】:

  • 啊,是的,我忘了说,但重点是不必这样做。
  • 我添加了一个会自动实现它的扩展,所以它只是将它添加到您的枚举声明中。 AFAIK 尽可能接近,直到 Swift 增加更多活力或更好的反思。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多