本文介绍了if-let Any到RawRepresentable< String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设:

enum MyEnum: String { case value }
let possibleEnum: Any = MyEnum.value
if let str = stringFromPossibleEnum(possibleEnum: possibleEnum)

在不知道枚举类型名称的情况下实现stringFromPossibleEnum的最佳选择是什么?

What's my best bet of implementing stringFromPossibleEnum without knowing enum type name?

func stringFromPossibleEnum(possibleEnum: Any) -> String? {
//    how should this be implemented without knowing enum type name?
}

UPD:好的,这越来越好了,我可以判断possibleEnum是否为枚举:

UPD: ok, it's getting better, with this I can tell if possibleEnum is an enum:

if Mirror(reflecting: possibleEnum).displayStyle == .enum { print("yes!") }

但是如何分辨这是否是基于String的枚举?

But how to tell if that's a String-based enum?

UPD : 此推文建议您获得rawValue为枚举中的任何".然后,您可能可以检查rawValue是否为String.但是如何从Mirror获取rawValue?

UPD: this tweet suggests that you can get rawValue as Any from Enum. You can probably then check if that rawValue is String. But how to get rawValue from Mirror?

推荐答案

好,因此目前基本上无法使用,因为您不能as? -cast到RawRepresentableMirror不为枚举提供rawValue.

Ok, so this is basically not doable currently out of the box, as you can't as?-cast to RawRepresentable, and Mirror does not provide rawValue for enums.

我想说最好的选择是制作自己的protocol,为基于StringRawRepresentable提供默认实现,并手动遵循所有枚举,如下所示:

I'd say the best bet is to make own protocol, provide default implementation for String-based RawRepresentable and conform all enums manually like so:

假设这些是枚举:

enum E1: String { case one }
enum E2: String { case two }
enum E3: String { case three }

StringRawRepresentable协议和默认实现:

protocol StringRawRepresentable {
    var stringRawValue: String { get }
}

extension StringRawRepresentable
where Self: RawRepresentable, Self.RawValue == String {
    var stringRawValue: String { return rawValue }
}

使所有需要的现有枚举符合协议:

Conform all needed existing enums to the protocol:

extension E1: StringRawRepresentable {}
extension E2: StringRawRepresentable {}
extension E3: StringRawRepresentable {}

现在我们可以强制转换为StringRawRepresentable:

And now we can cast to StringRawRepresentable:

func stringFromPossibleEnum(possibleEnum: Any) -> String? {
    if let e = possibleEnum as? StringRawRepresentable { return e.stringRawValue }
    return nil
}

stringFromPossibleEnum(possibleEnum: E2.two as Any)

这篇关于if-let Any到RawRepresentable< String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:43