1
votes

I'm trying to set the rawValues of an enum depending on whether the device is an iPhoneX or not, which I have stored as a boolean, isiPhoneX. If isiPhoneX is true, I want the rawValue to be 0.0, and if not, 1.0. It seems like having the ternary operator doesn't conform to rawValue. but are there any workarounds/solutions to this problem?

public enum Angles: Double {
   case angle1 = isiPhoneX ? 0.0 : 1.0
}

I get the following error messages:

'Angles' declares raw type 'Double', but does not conform to RawRepresentable and conformance could not be synthesized

Enum case must declare a raw value when the preceding raw value is not an integer

Raw value for enum case must be a literal

UPDATE: I didn't mention that I also have other cases in which I don't need the ternary logic, which I realize is now relevant. A more accurate example:

public enum Angles: Double {
   case angle1 = isiPhoneX ? 0.0 : 1.0
   case angle2 = 5.0
   case angle3 = 6.0
}
2

2 Answers

4
votes

RawValue has to be decided compile time. You can have calculated properties where you can put your custom logic in a switch case, like this:

public enum Angles {
   case angle1

    var doubleValue: Double {
        switch(self) {
            case .angle1: return isiPhoneX ? 0.0 : 1.0
        }
    }
}
0
votes

You could use associated values instead

public enum Angles {
    case angle1(Double)
}

And use it like this

let angle = Angles.angle1(isiPhoneX ? 0.0 : 1.0)

switch angle {
case .angle1(let value):
    print(value)
 }