syedfa syedfa - 19 days ago 4x
iOS Question

Trying to work with an enum that has duplicate values in Swift

I have an enum of type String which needs to have multiple variables that have the same value. My enum looks something like this:

class MyClass {

enum MyEnum: String {
case blahA = "blaha"
case blahB = "blahb"
static var blahD = "blah"
static var blahE = "blah"

The reason why I'm using static var's in the above construction is because both "blahD" and "blahE" need to reference the same String value, used in different places (don't ask me why, it just has to be this way). However, I have a method where I need to pass in the value of the enum as follows:

if let testString = myString(foo: MyEnum.blahD) {...}

I unfortunately am getting the following compilation error:

"Cannot convert value of type "String" to expected argument type "MyClass.MyEnum".

How do I get around passing the above variable which has duplicate values in my enum in the method, but cast it to the type of "MyClass.MyEnum"?

Thanks in advance to all who reply.


If the function takes a value of type MyEnum, you cannot do this. The type properties blahD and blahE are simply not of that type. Only the cases of the enum are of type MyEnum.

The function parameter's type must be changed to String.

The only other way around it would be to add a case to the enum that has a raw value matching the value of those two properties: case blahDOrE = "blah". Then you could construct that case: MyEnum(rawValue: MyEnum.blahD), but I can't see that being very useful.