[英]I want to return a RawRepresentable's rawValue as an Any, but I only receive it as an Any
so I have a function which receives an Any
and it checks if the Any is an enum by using reflection: 所以我有一个函数,它接收
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
}
Does anyone know how I can accomplish something like that? 有谁知道我能完成这样的事情吗?
I think the Swifty way to do this is to use a protocol for the enums you want to use: 我认为执行此操作的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"
This should allow you to do what you need, but keep Type safety. 这应该允许您执行所需的操作,但要保持Type安全。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.