if-let Any to RawRepresentable

后端 未结 2 506
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 05:07

Let\'s assume this:

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


        
2条回答
  •  [愿得一人]
    2021-01-14 05:55

    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.

    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:

    Assuming these are the enums:

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

    StringRawRepresentable protocol and default implementation:

    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 {}
    

    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)
    

提交回复
热议问题