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
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
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
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.