(You could off course use some custom generic wrapping type other than Optional
but I guess that's not what you're looking for either.)
It might be interesting to note that cases with associated values are functions from their associated value's type to the enum type (MyEnum
in this case):
print(type(of: MyEnum.valueNone)) // MyEnum
print(type(of: MyEnum.valueString)) // (String) -> MyEnum
print(type(of: MyEnum.valueExpensive)) // (CustomDataTypeThatsExpensiveToConstruct) -> MyEnum
So you could implement what afaics is essentially your "static" property associatedValueTypeString
(only as a free function) like this:
func uglyWorkaround<T>(_ v: T) -> String {
switch v {
case is (MyEnum):
return "none"
case is (String) -> (MyEnum):
return "string"
case is (CustomDataTypeThatsExpensiveToConstruct) -> (MyEnum):
return "custom"
default:
preconditionFailure("Unhandled argument")
}
}
print(uglyWorkaround(MyEnum.valueNone)) // none
print(uglyWorkaround(MyEnum.valueString)) // string
print(uglyWorkaround(MyEnum.valueExpensive)) // custom
But your underlying concrete problem can probably be better solved using some totally different approach.