Reputation: 3926
I have two simple enums like this:
enum Bar:String {
case obj1 = "Object1"
}
enum Foo:String {
case obj2 = "Object2"
}
I want to write a function that takes enum case as param and it should print the case raw value. Something like this:
printCase(Bar.obj1) // prints "Object1"
printCase(Foo.obj2) // prints "Object2"
I tried like this but it takes the whole enum as param. But my case is different from it. Any help would be appreciated.
Thanks
Upvotes: 0
Views: 1369
Reputation: 271040
The linked question is actually quite close - you just have to change the parameter type to just T
, instead of T.Type
:
func printCase<T : RawRepresentable>(_ e: T) where T.RawValue == String {
print(e.rawValue)
}
Since you are accepting an instance of the enum, not the enum type itself.
Of course, you don't have to restrict this to enums where T.RawValue == String
, since print
can print Any
thing.
Upvotes: 2
Reputation: 54706
You just need to define a generic function that takes a RawRepresentable
and returns its rawValue
property.
func rawValue<T: RawRepresentable>(of case: T) -> T.RawValue {
`case`.rawValue
}
rawValue(of: Foo.obj2) // "Object2"
rawValue(of: Bar.obj1) // "Object1"
Upvotes: 1