2

I have a variable of type Any?. I'm totally know what that variable is type of enum: String. How I can get rawValue something like:

var somevar: Any? = someValue
(somevar as ?????).rawValue
  • https://stackoverflow.com/questions/32952248/get-all-enum-values-as-an-array. See this post I hop helps to you – AtulParmar Dec 05 '18 at 12:54
  • 2
    If you *totally* know that the variable is a `String` enum, why do you declare it as `Any`? You are fighting the strong type system. Be always as specific as possible not the contrary. – vadian Dec 05 '18 at 14:00

2 Answers2

1

First of all sorry I misunderstood your question.

Yes it is possible and very EASY

it is beauty of swift

You have to add some extra step there

Step1 :

Add protocol

protocol TestMe {
    var rawValueDesc: String {get}
    
}

Step 2 :

In your enum implement it

 enum YourEnum:String,TestMe {
        case one = "test"
        case two = "test1"
        
        var rawValueDesc: String {
            return self.rawValue
        }
        
    }

Finally

    var testdd:Any = YourEnum.one
    if let finalValue =   testdd as? TestMe {
       print( finalValue.rawValueDesc)
    }
    

Hope it is helpful to you

Community
  • 1
  • 1
Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
0

Assuming you have this defined somewhere in your or in imported module:

enum First: String {
    case a, b
}

enum Second: String {
    case c, d
}

In you module your should do something like this:

protocol StringRawRepresentable {
    var rawValue: String { get }
}

extension First: StringRawRepresentable {}
extension Second: StringRawRepresentable {}

And here's your problem:

var somevar: Any? = someValue
let result = (somevar as? StringRawRepresentable)?.rawValue

If, for example, someValue == Second.c you gonna get "c" in result.

This approach will work, but you will have to extend all the possible types, otherwise as? casting will result in nil even if type has rawValue: String property.

brainray
  • 12,512
  • 11
  • 67
  • 116
user28434'mstep
  • 6,290
  • 2
  • 20
  • 35