swift - I want to return a RawRepresentable's rawValue as an Any, but I only receive it as an Any -


so have function receives any , checks if enum using reflection:

func extractrawvalue(subject: any) throws -> {     let mirror = mirror(reflecting: subject)      guard let displaystyle = mirror.displaystyle,         case .`enum` = displaystyle else {             throw errors.noenum     }      // , here don't know how go further...     // wish this:     guard let subject = subject as? rawrepresentable let rawvalue = subject.rawvalue else {         throw errors.norawrepresenable     }      return rawvalue  } 

does know how can accomplish that?

i think swifty way use protocol enums want use:

protocol valueasanyable {     func valueasany() -> }  extension valueasanyable self: rawrepresentable {     func valueasany() -> {         return rawvalue     } }  func extractrawvalue(subject: any) throws -> {     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: = testenum.test let thing = try? extractrawvalue(subject: subject) //prints "test" 

this should allow need, keep type safety.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -